We had a discussion at work about code design and one of the issues was when handling responses from a call to a boolean method like this:
bool ok = IsEverythingOK();
if(ok)
{
//do somehthing
}
One of my colleagues insists that we skip the extra variable ok and write
if(IsEverythingOK())
{
//do somehthing
}
Since he says that using the "bool ok"-statement is memorywise bad.
Which one is the one we should use?
Paraphrasing your question:
Is there a cost to using a local variable?
Because C# and .NET is well-engineered my expectation is that using a local variable as you describe has no or a negligible cost but let my try to back this expectation by some facts.
The following C# code
if (IsEverythingOk()) {
...
}
will compile into this (simplified) IL (with optimizations turned on)
call IsEverythingOk
brfalse.s AfterIfBody
... if body
Using a local variable
var ok = IsEverythingOk();
if (ok) {
...
}
you get this optimized (and simplified) IL:
call IsEverythingOk
stloc.0
ldloc.0
brfalse.s AfterIfBody
... if body
On the surface this seems slightly less efficient because the return value is stored on the stack and then retrived but the JIT compiler will also perform some optimizations.
You can see the actual machine code generated by debugging your application with native code debugging enabled. You have to do this using the release build and you also have to turn off the debugger option that supresses JIT optimizations on module load. Now you can put breakpoints in the code you want to inspect and then view the disassembly. Note, that the JIT is like a black box and the behavior I see on my computer may differ from what other people see on their computers. With that disclaimer in mind the assembly code I get for both versions of the code is (with a slight difference in how the call is performed):
call IsEverythingOk
test eax,eax
je AfterIfBody
So the JIT will optimize the extra unnecessary IL away. Actually, in my initial experiments the method IsEverythingOk
returned true
and the JIT was able to completely optimize the branch away. When I then switched to returning a field in the method the JIT would inline the call and access the field directly.
The bottom line: You should expect the JIT to optimize at least simple things like transient local variables even if the code generates some extra IL that seems unnecessary.
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