Array performance

I’ve been reading about dynamic arrays in C. Fun bed time reading right? It has got me thinking about arrays in Xojo however.

Let’s say I have a need for a dynamically-growable array of UInt8.

// Define
Var bytes() As UInt8
// Add a new byte

Is it more performant to allocate a certain amount of elements up front (accepting that uses more memory) and insert into an empty index or call AddRow?

// Sloppy code but you get the gist. 
Var bytes(1000) As UInt8
Var pos As Integer = 0
Var lastIndex As Integer = 999

bytes(pos) = 10
pos = pos + 1
If pos > lastIndex Then
lastIndex = 1999
End If

I believe that you will find pre-allocating the array is quicker

As far as I recall append will grow the array in “chunks” but it has to do it by using realloc (I think thats what it uses) which grows it in place (again I think this is the case)
And if it cant grow it in place it may perform even worse

Pre-allocating skips all those reallocs

1 Like

From experience I can tell you that dimming the array to the preferred size is quicker than appending during population.

For arrays to which I don’t know the size to begin with, I over dim, then redim at the end.

1 Like

Thanks guys, that confirms my suspicions. Man, writing a compiler in Xojo is hard. All these little performance hacks add up.

One reason Xojo’s compiler wssnt written in Xojo
Plus LLVM makes it way simpler to target difference CPU’s etc