Home > Articles > Programming > C/C++

Optimizing Objective-C

  • Print
  • + Share This
Objective-C was created as a compromise, trying to combine the speed of C and the flexibility of Smalltalk. David Chisnall shows how to avoid the slower parts of the language in the hot parts of your code.
From the author of

Objective-C was designed to be a compromise between the flexibility of Smalltalk and the power of C. It adds some dynamic behavior on top of C, while still allowing you to use C for activities that depend on speed.

Often, you'll write some code using all of the dynamic flexibility of Objective-C, and then start wondering if you can make it faster. The first step in improving speed is always profiling—see how much time is being spent in the various parts of a program, and optimize Objective-C overhead only if that's really where your program is spending most of its time.

Once you've found hot spots, there are several ways to avoid them. This article examines those techniques.

Testing Equality

It's quite common to see code like this in an Objective-C program:

if ([someValue isEqual: someOtherValue])

This line sends an -isEqual: message to test for equality. The first thing that most equality-testing methods do is test for identity: Two objects that are the same object are obviously equal. If the variables are likely to be the same object, you can move this identity test outside of the message send, like this:

if ((someValue == someOtherValue) || [someValue isEqual: someOtherValue])

This approach can avoid the cost of sending a message (a bit more than the cost of a function call) if the two objects are the same. This is especially important when you're comparing values against specific keys provided by the system. These are typically constant strings, identified by global values prefixed by the lowercase letter k.

These keys are used all over the place in Cocoa, and often you'll need to test whether a particular key or similar value is returned. Because the key is a constant, the pointer comparison will almost always work.

  • + Share This
  • 🔖 Save To Your Account