This is the most readable and highest performing version of the function.
int calcme(int a, int b)
{
return a*20 + b;
}
If you put a constant in a static
variable, maybe the compiler will figure out that it's never changed, and convert it to an immediate operand. Maybe the compiler won't figure it out and it will load the static from memory.
If you put a constant in a global variable, the compiler WILL load the variable from memory.
You are trying to outsmart the optimizer, and this is almost always a bad idea.
Here is your original code, compiled:
leal (%rdi,%rdi,4), %edi
leal (%rsi,%rdi,4), %eax
ret
This is the same code generated by return a*20 + b;
, but your code is more difficult to read. Note that the static variable doesn't actually get stored anywhere, it gets converted to an immediate operand (and then strength reduction reduces it even further). You'll get the same exact performance from the following code:
int calcme(int a, int b)
{
int local = 20; // "initialized" every time the function is called
// yet the assembly is the same
return a*local + b;
}