In my app, I’m using both strategies:
-
I have a
Utils
class, it only has class methods that I call for doing common global methods, likeNSString
validation, etc. -
I have an app-wide singleton class which I instantiate during app Did Finish Launching, and use this throughout the app to hold global objects / state, perform long-running processes, etc.
My question is, in the terms of performance which approach is better? I’m happy with both the approaches, but I can do an inexpensive, but effortful migration to move all the Utils class methods to instance methods in the app-wide singleton if this would give me performance gains. The Utils methods get called a lot in my app, but I don’t really notice any performance penalties in Instruments.
Likewise, I can go the other way and move at least a few of the somewhat general purpose functions I end up adding to the singleton to now be class methods in the Utils
class as well.
Does any Objective-C guru have some concrete benchmarks or even strong opinions on which approach is more performant?
2
To start with if you really need to shave those extra few nanoseconds off your Utils
C++ functions (potentially inlined) are probably the fastest thing on offer to you.
As to the question of whether class methods or singleton instance methods are more performant I will not claim to know for sure but a quick look at the objective-c runtime shipped with OSX 10.10 shows that _class_getClassMethod
calls _class_getInstanceMethod
which might lead you to think that instance methods would be faster.
Looking into this further I found that _object_getMethodImplementation
calls _class_getMethodImplementation
. Which would point to class methods being slightly faster to load.
All this is pretty moot though as in any instance you have 1 or 2 more function pointer accesses. This would only be noticeable if your methods are being called at least millions of times (and at that point optimising your method implementations is probably time better spent).
Stylistically, I agree with what you currently have, using singletons where state is required and class methods where it is not.
2