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.
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.
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.