What is the advantage of using arrayWithCapacity than using an array?

There is no need to specify the size of the array when creating the array, right? Then why do we need arrayWithCapacity? And if I set the size of the array smaller than necessary, is that normal?

+5
source share
2 answers

arrayWithCapacity is an optimization - it's optional. If you know the number of elements ahead of time, the system can allocate memory in one system call and in one memory block. Otherwise, the system will have to resize the array later, adding a few more elements and, as a rule, slowly, requiring additional allocations and, possibly, copying data from the old buffer to the new buffer.

+6
source

arraycreates an empty array (and allocates memory when adding an object), while it arrayWithCapacitycreates an array with enough memory allocated to store these objects, but you can always expand it when necessary.

+1
source

All Articles