ToniAz ToniAz - 2 months ago 19
C++ Question

Overloading operator body contains only one function call

I have this function

int add(T a, T b)
{
return a.blah +b.blah;
}


And I want to overload the plus operator and I have to options (of course, in this case the plus operator already accomplishes what the following code does)

Option 1:

int operator+(T lhs, T rhs)
{
return add(a,b);
}


Option 2:

int operator+(T lhs, T rhs)
{
return a.blah+b.blah;
}


Does any of those definitions have a performance edge over the other? Something to not is that the function I am trying to implement performs a more complicated operation on the elements of an STL container.

Answer Source

Use option 1, do not repeat yourself. Make sure the compiler sees the definition of add when you define operator+ so it can inline the code. There will be absolutely no difference in the generated code when optimizations are turned on.

struct T
{
    int blah;
};

int add(T a, T b)
{
  return a.blah +b.blah;
}

int operator+(T lhs, T rhs)
{
  return add(lhs, rhs);
}

GCC generates:

add(T, T):
  lea eax, [rdi+rsi]
  ret
operator+(T, T):
  lea eax, [rsi+rdi]
  ret

https://godbolt.org/g/g1ypni

Clang and the Microsoft compiler generate the same code.

If the code is more complex and the compiler refuses to inline add into operator+, consider making operator+ an inline function. Then it will get inlined since it does just one call and the caller will directly call add without additional overhead.

The usual admonition: You should of course as always benchmark to see if there is any real difference and profile to see what is causing the difference, also look at the generated code to check whether optimizations are performed as you expect :-)