Feeds

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

Runtime efficiency issues in Mac Cocoa programming

Secure remote control for conventional and virtual desktops

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.

Choosing a cloud hosting partner with confidence

More from The Register

next story
PEAK APPLE: iOS 8 is least popular Cupertino mobile OS in all of HUMAN HISTORY
'Nerd release' finally staggers past 50 per cent adoption
Microsoft to bake Skype into IE, without plugins
Redmond thinks the Object Real-Time Communications API for WebRTC is ready to roll
Microsoft promises Windows 10 will mean two-factor auth for all
Sneak peek at security features Redmond's baking into new OS
Mozilla: Spidermonkey ATE Apple's JavaScriptCore, THRASHED Google V8
Moz man claims the win on rivals' own benchmarks
Yes, Virginia, there IS a W3C HTML5 standard – as of now, that is
You asked for it! You begged for it! Then you gave up! And now it's HERE!
FTDI yanks chip-bricking driver from Windows Update, vows to fight on
Next driver to battle fake chips with 'non-invasive' methods
DEATH by PowerPoint: Microsoft warns of 0-day attack hidden in slides
Might put out patch in update, might chuck it out sooner
Ubuntu 14.10 tries pulling a Steve Ballmer on cloudy offerings
Oi, Windows, centOS and openSUSE – behave, we're all friends here
prev story

Whitepapers

Why and how to choose the right cloud vendor
The benefits of cloud-based storage in your processes. Eliminate onsite, disk-based backup and archiving in favor of cloud-based data protection.
Getting started with customer-focused identity management
Learn why identity is a fundamental requirement to digital growth, and how without it there is no way to identify and engage customers in a meaningful way.
High Performance for All
While HPC is not new, it has traditionally been seen as a specialist area – is it now geared up to meet more mainstream requirements?
Storage capacity and performance optimization at Mizuno USA
Mizuno USA turn to Tegile storage technology to solve both their SAN and backup issues.
Internet Security Threat Report 2014
An overview and analysis of the year in global threat activity: identify, analyze, and provide commentary on emerging trends in the dynamic threat landscape.