Feeds

Don't forget the ‘C’ in Objective-C

Runtime efficiency issues in Mac Cocoa programming

The Power of One Brief: Top reasons to choose HP BladeSystem

Part One Nowadays, it’s all too easy to take today’s fast processors for granted. At the risk of sounding like an old fogey, I get the impression that a lot of developers do just that. This devil-may-care attitude is not, in my opinion, the result of complacency but far more likely due to inexperience or even – dare I say it? – ignorance.

Just as a good driver has a certain understanding of, and empathy with, the mass of rotating, reciprocating hardware a few feet in front of him, I reckon the best programmers have some ‘feel’ for the way in which their code is mapped onto machine code instructions; an understanding of the demands they’re making on the processor, if you will.

I’ve felt this way for some time, but the point was recently hammered home while I was browsing around inside the internals of a certain Mac OS X utility – as one does. The programmer in question wanted to use OpenGL effects in his application, and in order to do that, he needed to establish the capabilities of the installed OpenGL system. In particular, the developer wanted to check for the presence of the GL_EXT_texture_rectangle extension which, as you probably know, indicates that borderless, 2D rectangular textures are supported.

The conventional way of doing this is to make the following call:

char *extensions = glGetString(GL_EXTENSIONS);

This will give you a plain-vanilla C string containing a list of all the available extensions. Having got hold of this string, here’s what our anonymous Cocoa developer did; firstly, he used the NSString stringWithCString: method to convert the C string into an instance of NSString. (This particular method is deprecated in Tiger, by the way, but let’s not go into that). Next, he used the componentsSeparatedByString: method to chop the string up into an array of its component parts – this relies on the fact that there’s a space between each extension name. Finally, he used the containsObject: method of the NSArray class to look for the string ‘GL_EXT_texture_rectangle’.

OK – I’m not disputing the fact that this code works, but to me, it seems a really roundabout way of doing things. For starters, a more experienced Mac programmer would simply have used the rangeOfString: method to determine whether the wanted extension name was present; this would have eliminated the need to chop the original string into a list of separate extension names. Of course, we’d still have to first use stringWithCString: to convert our original C string into an instance of NSString. Surely, there’s a better way?

Cutting to the chase…

Sure there is. As the title of this article points out, Objective-C is built on top of C, and the C runtime language has a perfectly good, tried and trusted runtime library routine for finding one string within another! All of the above convoluted shenanigans can be replaced with this:

BOOL gotTexturedRects
    = strstr(glGetString(GL_EXTENSIONS), "GL_EXT_texture_rectangle")
      != nil;

I guarantee that the above statement will execute far more quickly than the aforementioned alternative. Why? Because this code involves exactly two native subroutine calls while the Cocoa alternative makes an assortment of calls, both inside and outside the Cocoa frameworks, and of course each time you use a Cocoa message, the Objective-C dispatcher is invoked to figure out which actual routine to call.

To be clear: I’m not knocking Cocoa or Objective-C here. All I’m saying is that a little familiarity with the underlying C runtime library can translate into big dividends in performance terms. Determining the capabilities of the OpenGL system is something that you’ll typically do once only, in the initialisation part of your program. But looking for one string inside another is something that you might do tens of thousands of times inside a text crunching application. Using strstr as I’ve shown here, we cut right to the chase.

As a general rule, if you’re working with an API which expects/returns C-style strings (such as OpenGL) then it’s often much quicker to use a standard C library routine than it is to convert the string into an NSString class before doing the necessary. For example, if some non-Cocoa API hands you a C string and you need the length of it, only a complete Cocoa-headed klutz would do this:

NSString *str = [NSString stringWithCString: myCString 
                 encoding: [NSString defaultCStringEncoding]];
int len = [str length];

You might think I’m exaggerating, but I have seen code that does this. My friend, let me introduce you to strlen

Again, don’t get me wrong: NSString has lots of advantages when compared to a barefoot C string; built in support for Unicode being a key benefit. At the risk of making sweeping generalisations, Mac programmers tend to be far more oriented towards creating language-neutral, easily localisable applications than is the case on the Windows platform. Part of the reason for this lies in the flexibility of NSString – hence the reference to encoding formats in the above code snippet. But don’t break out the Cocoa sledgehammer when you’re working with C strings; the runtime library will often have done the job by the time you’ve created your first NSString instance.

Next time round, we’ll be looking at other Cocoa programming issues from a runtime efficiency perspective, and I’ll be looking at ways in which Cocoa applications can be structured more effectively.

Securing Web Applications Made Simple and Scalable

More from The Register

next story
Whoah! How many Google Play apps want to read your texts?
Google's app permissions far too lax – security firm survey
Chrome browser has been DRAINING PC batteries for YEARS
Google is only now fixing ancient, energy-sapping bug
Do YOU work at Microsoft? Um. Are you SURE about that?
Nokia and marketing types first to get the bullet, says report
Microsoft takes on Chromebook with low-cost Windows laptops
Redmond's chief salesman: We're taking 'hard' decisions
EU dons gloves, pokes Google's deals with Android mobe makers
El Reg cops a squint at investigatory letters
Big Blue Apple: IBM to sell iPads, iPhones to enterprises
iOS/2 gear loaded with apps for big biz ... uh oh BlackBerry
OpenWRT gets native IPv6 slurping in major refresh
Also faster init and a new packages system
Google shows off new Chrome OS look
Athena springs full-grown from Chromium project's head
prev story

Whitepapers

Top three mobile application threats
Prevent sensitive data leakage over insecure channels or stolen mobile devices.
The Essential Guide to IT Transformation
ServiceNow discusses three IT transformations that can help CIO's automate IT services to transform IT and the enterprise.
Mobile application security vulnerability report
The alarming realities regarding the sheer number of applications vulnerable to attack, and the most common and easily addressable vulnerability errors.
How modern custom applications can spur business growth
Learn how to create, deploy and manage custom applications without consuming or expanding the need for scarce, expensive IT resources.
Consolidation: the foundation for IT and business transformation
In this whitepaper learn how effective consolidation of IT and business resources can enable multiple, meaningful business benefits.