Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obj-C: Class methods vs instance methods -- efficiency difference?

For the sake of tidiness and reusability, I'm thinking about putting a bunch of utility methods inside a single class. The class does not require any properties of its own and so I will define the methods as class methods; I figure that's there's no real need to have an instance of this class floating around…

…or is there? Is there a difference in efficiency? (A noticeable one?) Or does calling class methods behave in the same way as if they were part of the calling class?

like image 561
Oliver Avatar asked Dec 06 '22 03:12

Oliver


1 Answers

dandan78 has the correct answer in general. It's always best to measure your code yourself. In fact, for this problem, you should probably just implement it the way you want, and then measure, and only change it if it's significantly slowing down your app.

Gavin is also correct that C functions are more efficient than class or instance methods. But again, unless you're calling these methods millions of times in a tight loop, the overhead of a method vs a C function probably won't matter to your application.

But to answer the question asked, there's basically no difference between class methods and instance methods. In Objective-C, classes are actually objects themselves, and sending messages to them is identical to sending a message to an instance object. Each class basically has a singleton object that class methods are called on.

like image 139
Michael Buckley Avatar answered Feb 16 '23 02:02

Michael Buckley