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 darkfeline on Sunday August 25 2019, @09:26PM (1 child)
One of the nice features of Go is that it has real constants. Consts are analogous to macros in that they are rendered at compile time.
Some effects of this:
1. You can't take a pointer to a const, since a const doesn't exist in memory; its literal value is inserted where it's present in the code.
2. Numeric consts have infinite precision and are unbounded. You can make consts far greater than an int64 for example, and division is exact. Of course, if you try to assign such a const to a variable the value will get truncated.
3. The compiler can reason about consts, e.g. for pruning branches.
Join the SDF Public Access UNIX System today!
(Score: 0) by Anonymous Coward on Monday August 26 2019, @08:08AM
So does C++. They are just called constexpr
const is from the old days and like everything else legacy, it has history and "reasons". If you want real constants that are not macros, use constexpr.