简体   繁体   中英

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?

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创建一个空数组(并在添加对象时分配内存),而arrayWithCapacity创建一个数组,其中分配了足够的内存来容纳这些对象,但您可以在需要时随时展开它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM