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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With