Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using a static member function instead of an equivalent non-static member function?

I was wondering whether there's any advantages to using a static member function when there is a non-static equivalent. Will it result in faster execution (because of not having to care about all of the member variables), or maybe less use of memory (because of not being included in all instances)?

Basically, the function I'm looking at is an utility function to rotate an integer array representing pixel colours an arbitrary number of degrees around an arbitrary centre point. It is placed in my abstract Bullet base class, since only the bullets will be using it and I didn't want the overhead of calling it in some utility class. It's a bit too long and used in every single derived bullet class, making it probably not a good idea to inline. How would you suggest I define this function? As a static member function of Bullet, of a non-static member function of Bullet, or maybe not as a member of Bullet but defined outside of the class in Bullet.h? What are the advantages and disadvantages of each?

like image 723
jonathanasdf Avatar asked May 01 '10 05:05

jonathanasdf


2 Answers

There is absolutely no performance difference between static member functions and free functions.

From a design perspective, it sounds like the function in question has very little to do with Bullets, so I would favour putting it in a utility library somewhere, there is no runtime overhead in doing this, only extra developer effort if you don't already have such a library.

Regarding the original question, if the function doesn't obviously pertain to a particular class, then it should be a free function. At the most, it should belong to a namespace, to control its scope. And even if it pertains to a class, most times, I would still prefer the free function unless the function requires access to private members.

like image 176
Marcelo Cantos Avatar answered Sep 24 '22 22:09

Marcelo Cantos


Typically static is used if possible, to eliminate the need for an object and eliminate the extraneous this argument.

But one exception is in functors: classes which define operator() so objects can be "called" as functions. Idiomatically such an operator() is declared inside the class {} block, which makes it inline.

Then, if the function is small, it is inlined into the calling function and the this pointer is optimized out.

If the function is large, it may not be inlined. But the miniscule disadvantage of having an extra argument is probably dwarfed anyway.

like image 30
Potatoswatter Avatar answered Sep 24 '22 22:09

Potatoswatter