Array size allocation in Xojo
When you allocate an array in Xojo, you may wonder how many bytes are allocated and when.
We measured a bit and it looks like allocating an empty array will just allocate the array structure, but not allocate data for the array values. Then when you append the first value, the memory is allocated for 16 values, byte size depending on byte size of elements. Then whenever the appended values fills the allocated space, the allocation is resized to make room for more values. The number of values added is doubled each time as you see in our table:
From Ubound | Size in Bytes | Number of values | ∆ |
-1 | 0 | 0 | |
0 | 128 | 16 | 16 |
16 | 384 | 48 | 32 |
48 | 896 | 112 | 64 |
112 | 1920 | 240 | 128 |
240 | 3968 | 496 | 256 |
496 | 8064 | 1008 | 512 |
1008 | 16256 | 2032 | 1024 |
2032 | 32640 | 4080 | 2048 |
4080 | 65408 | 8176 | 4096 |
8176 | 130944 | 16368 | 8192 |
16368 | 262016 | 32752 | 16384 |
32752 | 524160 | 65520 | 32768 |
When you do a redim on the array, you set the allocated size to the array to an explicit value. So unless redim has already the value of ubound, a new memory block will be allocated and data is copied. There is no optimization to just change internal ubound and keep array allocation if e.g. size is just shrinking by one or two. We made a feedback request to ask for optimization: Feedback 58755.
What to do? Whenever you fill an array and you know the final ubound in advance, you can use redim beforehand and then set values. Otherwise you use append or insert methods which dynamically allocate new memory when you hit the current allocation limit.
