Could someone demystify arrays for me?

I was having trouble finding performance characteristics for push! and pushfirst! on Vector{T} so I wrote a quick test comparing the two and was surprised to find that they were the same speed - even when intermixed. I did my best to hunt around for the answer and got as far as this function in array.c until I decided I would give up and just ask.

When I allocate an empty array of size n, does it start adding to the middle instead of the front of the memory allocation? Doesn’t that have (admittedly small) performance implications for the usual case of just pushing things onto the end? Is there a way to change this behavior?

1 Like

Vectors (implemented jl_array_t) can have extra unused space before the elements (see the offset field in the C code). So pushfirst! will allocate extra space and only move/reallocate occasionally.

This is not exactly overdocumented, but it is mentioned in passing in the devdocs.

5 Likes