Pseudo Dynamic Arrays
Another idea:
In VB often I've used something that I call "Pseudo Dynamic Arrays"!
The huge problem with rediming arrays and copying all the data (to preserve the already saved elements) is:
It costs to much time!
So I
dimmed my "dynamic" array at the beginning at some convenient size (it doesn't really matter):
Dim PersonArray(32) As PersonType
And I introduced a variable to count the already saved elements:
Dim PersonArrayCount As Int
When I have to save a new entry I used some code to check whether there is still free space. If not: Create more space by redimming and copying!
And this is the essential trick:
Double the available space!
(Applying the principle of reverse binary search.)
Example:
Sub AddPerson(p As PersonType)
'Calc index of the new element:
PersonArrayCount = PersonArrayCount + 1
'Is there still free space?
If PersonArrayCount > PersonArray.Length Then 'No!
'In classic VB I would simply use this line:
' ReDim Preserve PersonArray(2 * PersonArrayCount)
'But "Preserve" does not exists in b4a, so do it manualy...
'Save the old data:
Dim PersonCache(PersonArray.Length) As PersonType
Dim i As Int
For i = 0 To PersonArray.Length - 1
PersonCache(i) = PersonArray(i)
Next'i
'Redim the array and copy the old data back:
Dim PersonArray(2 * PersonArrayCount) As PersonType
For i = 0 To PersonCache.Length - 1
PersonArray(i) = PersonCache(i)
Next'i
End If
'Finaly save the new element:
PersonArray(PersonArrayCount - 1) = p
End Sub
In this way the average extra cost remains very cheap and therefore the programm will run much faster!