Search code examples
c++performanceoptimizationconstantscompiler-optimization

Is f(int const) better than f(int) for compiler optimization?


Consider the following two functions:

void f(int n);

void f(int const n);

From the perspective of compiler optimization, the latter seems better than the former.

However, from the perspective of the caller, int const n has more useless information and more mental load than int n.

Which is the better practice?


Solution

  • TLDR: In practice, there will be zero performance benefits from doing this. Use const for clarity and readability, not performance.

    As const on function parameters is not even part of the function signature, both functions will have exactly the same calling convention, no matter your ABI. This means that there is zero benefit for callers.

    Inside the function itself, const doesn't help the compiler much either. Any compiler worth it's salt can figure out by itself whether you are modifying n.

    It's possible to construct pathological cases, where the const could allow the compiler to assume certain things. For example, that a nested function call, that we pass n as a (non const) pointer to, will not modify it. This could allow the compiler to do better store -> load forwarding and avoid spilling to the stack. As it stands, compiler don't even seem to take advantage of that though (https://godbolt.org/z/jGsKo56aG).