tags:

views:

212

answers:

2

Suppose I have an immutable NSArray and want to 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.

+2  A: 

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.

notnoop
I guess I will just write my own wrapper then.
DenNukem
A: 

Look at it in Instruments and see how much memory is allocated when you create the subarray.

NSResponder