Steven Smethurst
Steven Smethurst

Reputation: 4614

Static vs member functions in c++ is there an overhead

In a C++ class is there any overhead in having static function instead of a member functions.

class CExample
{
    public: 
        int foo( int a, int b) {
            return a + b ; 
        }
        static int bar( int a, int b) {
            return a + b ; 
        } 
};

My questions are;

Upvotes: 7

Views: 6189

Answers (4)

tletnes
tletnes

Reputation: 1998

bar MAY have less overhead in some compilers/situations since it will never need to be placed in a pointer table and will not need an extra "this" parameter.

the only reason to make foo non-static if it does not use local memebers is if you intend to overload it, but since it is not virtual this does not come into play.

Upvotes: 1

Prashant Kumar
Prashant Kumar

Reputation: 22509

This answer focuses addresses the second part of your question
Quoted from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices:

Chapter 44. Prefer writing nonmember nonfriend functions
[...] Nonmember nonfriend functions improve encapsulation by minimizing dependencies [...]

Scott Meyers proposes the following algorithm for determining which methods should be members of a class (source)

if (f needs to be virtual)
   make f a member function of C;
else if (f is operator>> or operator<<)
   {
   make f a non-member function;
   if (f needs access to non-public members of C)
      make f a friend of C;
   }
else if (f needs type conversions on its left-most argument)
   {
   make f a non-member function;
   if (f needs access to non-public members of C)
      make f a friend of C;
   }
else if (f can be implemented via C's public interface)
   make f a non-member function;
else
   make f a member function of C;

As for the first half of your question, I'd guess the compiler would optimize any difference away.

Upvotes: 6

Rafael Baptista
Rafael Baptista

Reputation: 11499

Probably there is no difference, because neither function accesses data members, and you don't derive from anything virtual.

But in the general case "bar" would be infinitessimally faster because "foo" as member function normally has to pass and use an additional argument - "this"

Upvotes: 0

Luchian Grigore
Luchian Grigore

Reputation: 258558

In this example is foo() or bar() more efficent?

No. Both calls are resolved statically. There may be some overhead in passing the this pointer to a non-static function, but in this case both will likely be inlined.

Why would I not want to make foo() in to a static function as it does not alter any member variables?

You wouldn't, it's actually good practice to make all methods not bound to an instance static.

Upvotes: 10

Related Questions