Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is advantage of using arrayWithCapacity than using array?

It is not necessary to specify array size when creating array, right? Then, why is arrayWithCapacity necessary? And if I set the size of array smaller than actually needed, is it OK?

like image 526
user698200 Avatar asked Aug 21 '11 21:08

user698200


2 Answers

arrayWithCapacity is an optimization - it is not necessary. If you know the number of elements ahead of time, the system can allocate storage in one system call and in one chunk of memory. Otherwise, the system has to resize the array later as you add more elements and that tends to be slow, requiring additional allocations and possibly copying data from the old buffer to the new buffer.

like image 132
EricS Avatar answered Oct 24 '22 01:10

EricS


array creates an empty array (and allocs memory when you add an object) while arrayWithCapacity creates an array with enough memory allocated to hold those objects, but you can always expand it when needed.

like image 34
Matt S. Avatar answered Oct 24 '22 00:10

Matt S.