Does subarrayWithRange create a copy when executed on immutable array (NSArray)?
Suppose I have an immutable NSArray and want to 开发者_JS百科create several sub-arrays. I could invoke subarrayWithRange on the original array and get a new NSArray. Does the new copy share memory region with the old copy?
In the worst case I may end up creating a sub-array for each element of the original array (starting with that element and ending at the end of the original array), so this makes a difference between a linear and a square memory use pattern.
It's unfortunate but Apple implementation isn't open source, so we cannot tell for sure. However, from simple testing it seems that it does create a new copy of the sub array.
While you are right that this may lead to square memory use pattern, it's also efficient in some cases. Imagine that you have a very large array, and you only want a small sub-array. The large array wouldn't be deallocate, if the subarray reuses the back-end array.
Look at it in Instruments and see how much memory is allocated when you create the subarray.
精彩评论