9

Is there any performance gain in calling C code from Objective-C?

I've read somewhere that message passing is slower compared to other languages that use function calling. So if I call a C function from Objective-C code, am I avoiding the messaging overhead?

When optimizing for performance, is it recommended practice to code the most critical functions and procedures in C instead of using Objective-C objects?

EDIT:
Given the amount of answers warning about premature optimization and code readability, I want to clarify that I was not thinking on regular applications, but very specific ones such as:

  • Graphics
  • Encryption or compression algorithms.
  • Maths

And in general, functions or procedures that do not need OO design and are intended to be called many times with parameters.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Mister Smith
  • 27,417
  • 21
  • 110
  • 193

5 Answers5

11

It's highly unlikely that you're writing code that's optimized enough for the bottleneck to be message sends. Write your code in the way that makes the most sense to you, then use Instruments to profile and optimize if necessary. Almost certainly, if your code is slow at all, it will be due to much higher-level problems than message sending.

andyvn22
  • 14,696
  • 1
  • 52
  • 74
  • OpenGL ES is coded in C, isn't it? That's a good example of the kind of code I'm talking about. – Mister Smith Mar 07 '12 at 17:06
  • Premature optimization is the root of all evil – Manlio Mar 07 '12 at 17:28
  • OpenGL is traditionally in C, but there are wrappers in many object-oriented languages, including Objective-C, which perform just fine. It's more about what you want your code to look like than how fast you want it to run. – andyvn22 Mar 07 '12 at 20:57
  • 1
    For many app types, early intelligent optimization of an app's algorithms and data types is required to get anywhere near a usable real-time response or frame rate. – hotpaw2 Mar 08 '12 at 02:33
  • 3
    While the principle of avoiding premature optimizations is correct, there are many cases in real products when message passing is a significant overhead and should be dealt with. You should strongly avoid message passing in tight loops that are called thousands of times or more. Unlike a method, a small function can be inlined, sometimes representing substantial performance gain (particularly when the compiler can apply secondary optimizations). You are correct that you should not prematurely optimize, but that doesn't mean it's not common to need to consider message sends. – Rob Napier Mar 08 '12 at 15:25
8

This is a benchmark that compares messaging to calling C functions. Here are the results of calling different implementations of the fibonacci function about 1.4 billion times.

Message Passing 23.495 seconds
IMP Calling     16.033 seconds
C Function      9.709 seconds

So yes, there is some overhead when calling an Objective C method. But, except in some situations, this is not what will impact the performance of your app. In fact, messaging is still more efficient than most other operations such as floating-point division.

In addition, the majority apps spend most time waiting for user input, downloading data, etc.

sch
  • 27,436
  • 3
  • 68
  • 83
  • Thanks, I was about to make my own benchmark. I know I should not take this approach from the begining. I was thinking on functions that are called a lot of times with more than one parameter, for instance, raytracing or heavy-weight encryption algorithms. So this makes sense. – Mister Smith Mar 08 '12 at 08:21
  • 1
    Finally I made my own benchmark, also using recursive fibonacci (but not the code shown in the link). Objective-C, even using C types (long, int) is 2,35 times slower than the C function. Definitely, coding up certain things in C it's well worth considering. – Mister Smith Mar 08 '12 at 14:06
4

Yes, it is recommended to use well-written plain C instead of using Objective C inside performance critical inner loops, such as real-time audio signal processing or image processing code. There is seldom any benefit to using object data types or messaging when dealing with thousands of individual audio samples, or millions of image pixels, per frame time. All the unneeded method dispatch cycles just waste the users battery life. Other types of complex numerical simulations and finite element models (etc.) might also benefit from keeping inner loops simple for best results from the compiler optimizer.

However, higher level stuff that only needs to happen a few times per event at a human pace likely doesn't consume enough message passing overhead cycles to be measurable. So any abstractions to improve code readability and reuse here are unlikely to cost the user any performance or battery life.

hotpaw2
  • 70,107
  • 14
  • 90
  • 153
1

An initial message is interpreted at run-time and as such takes about three times longer than a C++ virtual method call (which is itself slightly slower than a direct call). However subsequent calls are IMP cached and in most implementations are then faster than a C++ virtual method call, but still slightly slower than a direct function call (in C or C++).

So, yes there may be a performance gain, but before loosing all the benefits of Objective-C, you should be sure that the benefit of the "optimisation" is significant. In most cases greater performance benefits can be gained elsewhere; by employing suitable data structures and algorithms for example. Most code spends its time doing stuff rather in function call overhead - YMMV.

See Objective C message dispatch mechanism

Community
  • 1
  • 1
Clifford
  • 88,407
  • 13
  • 85
  • 165
1

Direct C function calling is always going to be faster than calling an Obj-C method; but, as many have pointed out, except in performance sensitive code it is unlikely to be a bottleneck.

However you can turn this around and ask why use a method if its slower? - the edict against "premature optimization" doesn't mean "write poor code on purpose".

Its a balance and the line between whether to use a method or function is fuzzy, you have to make the choice. Two endpoints which may help:

  1. If the code is going to be altering the state of the object - use a method.
  2. If the code is a natural function; takes some inputs, produces an output, doesn't manipulate state (have "side effects"); then a function makes sense.

For all the points in between use your own judgement.

For example, if you have a code in a class which needs to calculate the volume of a pyramid in multiple locations you abstract out the volume algorithm: method or function? Function - it takes some values, produces a value, doesn't alter the object state. Maybe even better is make it a static function, which effectively makes it private to the class and doesn't pollute your applications namespace. Writing such an algorithm as a method if it is only needed internally by the class is of no benefit - I'd say it was "poor code" to do so (but that is an opinion!)

CRD
  • 52,522
  • 5
  • 70
  • 86