Compilers can sometime exploit the fact that some 'variable' is a constant for optimization, so it's generally a good idea to use the "const" keyword when you can, but is there a tradeoff?
In short, is there a situation where using "const" might actually make the code slower (even a tiny bit)?
The const
keyword is used only during compile-time. After the code is compiled the variable is just an address in the memory, without any special protection.
There is some difference, however - global const
variables will be placed in the text
segment, not the data
(if initialized) or bss (if uninitialized). If the text
segment is treated differently, for example executed in place from a NOR flash memory (instead of RAM), there might be a difference. Local const
variables are placed on the stack together with the regular variables, so there should be no difference.
Other than that, as bestsss said, some compile time optimizations might be impossible if the variable is a constant. I can't really think of anything (especially not in pure C), but it is theoretically possible.
Edit:
The following code demonstrated the point in the second paragraph:
const int g = 1;
int not_const = 1;
void foo(int param)
{
int i = 1;
const int j = 1;
printf("Variable: \t\t0x%08x\n", (int)&i);
printf("Const varialbe: \t0x%08x\n", (int)&j);
printf("Parameter: \t\t0x%08x\n", (int)¶m);
printf("Global const: \t\t0x%08x\n", (int)&g);
printf("Global non-const: \t0x%08x\n", (int)¬_const);
}
In Visual Studio 2010, the result is as follows (note the big difference between the const and non-const global):
Variable: 0x002af444
Const varialbe: 0x002af440
Parameter: 0x002af43c
Global const: 0x00a02104
Global non-const: 0x00a03018
A combination of "const" and "non-const" objects can hurt you badly in a rather unexpected way. Some pseudocode:
//in some file far far away...
SomeType firstVariable;
const SomeType secondVariable;
here these variables look like they are located at adjacent addresses.
On many architectures they will be located far from each other since "const" variables will be placed in a special segment that has write protection during runtime. So interleaved access to those variables will result in more chache misses than you expect and this can considerably slow your program down.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With