Submitted via IRC for SoyCow3196
Why const Doesn't Make C Code Faster
In a post a few months back I said it's a popular myth that const is helpful for enabling compiler optimisations in C and C++. I figured I should explain that one, especially because I used to believe it was obviously true, myself. I'll start off with some theory and artificial examples, then I'll do some experiments and benchmarks on a real codebase: Sqlite.
Let's start with what I used to think was the simplest and most obvious example of how const can make C code faster. First, let's say we have these two function declarations:
void func(int *x);
void constFunc(const int *x);And suppose we have these two versions of some code:
void byArg(int *x)
{
printf("%d\n", *x);
func(x);
printf("%d\n", *x);
}void constByArg(const int *x)
{
printf("%d\n", *x);
constFunc(x);
printf("%d\n", *x);
}To do the printf(), the CPU has to fetch the value of *x from RAM through the pointer. Obviously, constByArg() can be made slightly faster because the compiler knows that *x is constant, so there's no need to load its value a second time after constFunc() does its thing. It's just printing the same thing. Right? Let's see the assembly code generated by GCC with optimisations cranked up:
(Score: 2) by cosurgi on Monday August 26 2019, @09:32AM (2 children)
> can be made slightly faster because the compiler knows that *x is constant
The compiler knows *x is constant only if you use constexpr [1], and optimizes for that. You will want to repeat all your benchmarks with this small fix. Remember that this works only if the value is known at compile time.
[1] https://en.cppreference.com/w/cpp/language/constexpr [cppreference.com]
#
#\ @ ? [adom.de] Colonize Mars [kozicki.pl]
#
(Score: 2) by turgid on Monday August 26 2019, @10:24AM
If you are coding in one of the modern and incredibly complex dialects of C++. C programmers know what they are doing,
I refuse to engage in a battle of wits with an unarmed opponent [wikipedia.org].
(Score: 0) by Anonymous Coward on Monday August 26 2019, @04:24PM
Completely untrue. In this case, const and constexpr will be equivalent.