What’s more efficient?
decimal value1, value2, formula
This:
for(int i = 0; i>1000000000000; i++);
{
value1 = getVal1fromSomeWhere();
value2 = getVal2fromSomeWhere();
SendResultToA( value1*value2 + value1/value2);
SendResultToB( value1*value2 + value1/value2);
}
Or this:
for(int i = 0; i>1000000000000; i++)
{
value1 = getVal1fromSomeWhere();
value2 = getVal2fromSomeWhere();
formula = value1*value2 + value1/value2;
SendResultToA(formula);
SendResultToA(formula);
}
Intuitively I would go for the latter…
I guess there’s a tradeoff between having an extra-assignment at each iteration (decimal, formula) and performing the computation on and on with no extra-variable…
EDIT :
Uhhh. God… Do I Have to go through this each time I ask a question ?
If I ask it, it is because YES it DOES MATTER to me, fellows.
Everybody does not live in a gentle non-memory-critical world, WAKE-UP !
this was just an overly simple example. I am doing MILLIONS of scientific computation and clouding multithreaded stuff, do not take me for a noob 🙂
So YES, DEFINITELY every nanosecond counts.
PS : I almost regret C++ and pointers. Automatic Memory Management and GC’s definitely made developers ignorant and lazy 😛
First of all profile first, and only do such micro optimizations if it’s necessary. Else optimize for readability. And in your case I think the second one is easier to read.
And your statement that the second code has an additional assignment isn’t true anyways. The result of your formula needs to be stored into a register in both codes.
The concept of the extra variable isn’t valid once the code is compiled. For example in your case the compiler can store
formulain the register wherevalue1orvalue2was stored before, since their lifetimes don’t overlap.I wouldn’t be surprised if the first one gets optimized to the second one. I think this optimization is called “Common subexpression folding”. But of course it’s only possible if the expression is free of side-effects.
And inspecting the IL isn’t always enough to see what gets optimized. The jitter optimizes too. I had some code that was quite ugly and slow looking in IL, but very short in the finally generated x86 code. And when inspecting the machine code you need to make sure it’s actually optimized. For example if you run in VS even the release code isn’t fully optimized.
So my guess is that they are equally fast if the compiler can optimize them, and else the second one is faster since it doesn’t need to evaluate your formula twice.