cocoacore-foundationfoundation

CoreFoundation vs Foundation


In iPhone development, speed is of the essence. Does anyone know if there is a speed difference between using a CoreFoundation type (like CFMutableDictionaryRef) versus a Foundation type (its counterpart, NSMutableDictionary).

I would think manipulating the CF type would be faster as it doesnt have to throw around ObjC runtime messages, is this an unfounded assumption, has anyone actually looked in to this?


Solution

  • In a technical sense, yes, it is faster, for exactly that reason.

    In a practical sense, no, it's not faster. For one thing, the speed difference is tiny. We're talking milliseconds saved over the life of the entire process.

    The savings might be bigger on the iPhone, but it's still pretty much the tiniest speed gain you can get. Your time is much better spent profiling your app in Instruments and going where it tells you and ironing out the hot spots in your own code.

    And that's where Foundation becomes faster: Your time.

    Code that uses Foundation's autorelease feature whenever feasible saves you a lot of time and headaches by avoiding easily-avoidable memory leaks (namely, forgetting to write or failing to reach release messages). CF does not have autorelease, so you have to remember to explicitly CFRelease everything you create or copy with it—and when you forget or fail to reach that code (and I do mean when—I speak from experience), you will spend much more time hunting down the memory leak. The static analyzer helps, but it will never be able to catch everything.

    (You technically can autorelease CF objects, but the code to do so is terribly ugly and you're only watering down your already-minuscule speed gain.)

    So, stick to Foundation as much as possible. Don't go overboard with the autorelease; even in pure Cocoa, there are still times when explicitly releasing objects is warranted (mostly tight loops), and this goes double for Cocoa Touch (since iOS will kill your app if you allocate too much memory, so you'll want to release big objects like images as soon as possible). But usually, autorelease saves you far more time than CF will ever save your users.

    The non-time-related reason is that Objective-C code, with argument names (from the message selector) mixed in with values, is far easier to read than C function-based code. This may not make your work go any faster, but it certainly makes it more fun.