1

I am writing an application that I'd like to speed up. One way I have thought to do this is by switching from using NSArray and NSMutableArray to using straight c-style arrays of pointers.

I had tried naively to just do:

MyObject** objects = (MyObject**) malloc(N/2*sizeof(MyObject*))

This reports a compiler error when using ARC as it doesn't know what to do with a ** object; this can be fixed by adding a bridge directive.

My question is how is this memory being handled and how to do memory management mixing C and Objective-C objects.

Two solutions are

MyObject* __weak* objects = (MyObject* __weak*) malloc(N/2*sizeof(MyObject*));

MyObject* __strong* objects = (MyObject* __strong*) malloc(N/2*sizeof(MyObject*));

What are the differences between those two arrays and how do I go about freeing/releasing them when done. Are NSArrays optimized to the point where this wouldn't result it much of a speed up?

5
  • 2
    CFArray is highly optimized (down to the ASM level). You need to look broader, and try not to micro-optimize like this, because now you've created a memory-headache and a pointer safety problem where there was a (minor) speed problem. Commented Apr 18, 2013 at 4:37
  • 1
    Profile. Don't speculate. Learn how to use Instruments. Check out Apple's developer videos for help getting started. Commented Apr 18, 2013 at 4:49
  • CodaFi: CFArray is actually somewhat slower than NSArray these days, and certainly not optimized "down to the asm level". It is very fast though, so not something I would blame without solid profiling data. Commented Apr 18, 2013 at 4:58
  • @Catfish_Man then CLANG's doing a darned good job of getting it down to that level. Commented Apr 18, 2013 at 5:17
  • It turns out that extreme simplicity plus a few tricks gets remarkably good codegen without having to go to great lengths :) Commented Apr 18, 2013 at 5:34

1 Answer 1

3

Are NSArrays optimized to the point where this wouldn't result it much of a speed up?

Yes.

You should profile your code in Instruments -- chances are that even if you make heavy use of arrays, you're going to find that your code spends most of its time in places other than NSArray methods like -objectAtIndex:.

Taking that a step further, you should really be able to tell us whether NSArray is optimized sufficiently that you don't need to improve it. If you're looking to speed up your code by replacing NSArray, you should have already profiled your code and identified the expensive parts. Don't just guess at what needs to be improved; measure it.

Sign up to request clarification or add additional context in comments.

1 Comment

Also -objectAtIndex: can often be replaced by bulk accessors like for(in)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.