Static vs member functions in C ++ are overhead

In the C ++ class, there is some kind of overhead when you have a static function instead of 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:

  • In this example, are foo () or bar () more efficient ?.
  • Why don't I want to include foo () in a static function as it does not change any member variables?
+5
source share
4 answers

In this example, are foo () or bar () more efficient?

No. Both calls are statically allowed. There may be some overhead when passing a thisfunction pointer not static, but in this case both will probably be nested.

Why don't I want to include foo () in a static function as it does not change any member variables?

, static.

+8


++ : 101 , :

44. non -ember nonfriend

[...] non-members nonfriend [...]

, ()
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 public interface)
   make f a non-member function;
else
   make f a member function of C;

, , .

+5

bar /, "this".

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

+1
source

There is probably no difference because none of the functions access data members and you are not getting anything virtual.

But in the general case, the β€œbar” will be infinitely faster, because β€œfoo” as a member function usually has to go through and use an additional argument - β€œthis”

0
source

All Articles