I've always heard that a good practice to ensure best performance was to:

  • pass fundamental types (int, double...) by value
  • pass classes by const reference

Nowadays, using C++11 and full optimizations under a compiler, is there an overhead when one passes a fundamental type by const reference?

And furthermore, when T is int will the following function:

template <typename T> inline void f(const T& x);

be slower than:

template <typename T> inline void f(const T x);
有帮助吗?

解决方案

If the compiler is really inlining the code (which is common for simple templates) there will be no difference. The problem becomes apparent when the function cannot be inlined, and the out-of-line definition is called.

In that case, passing a reference can involve an extra dereference when accessing the variable (at the very least the first time, possibly multiple times) At the same time, the compiler can perform more aggressive optimizations if the argument is by value, since it knows that the variable cannot be accessed/modified outside of the current function.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top