Is there a performance penalty when using an extra local variable to store a method's result?
public string void ToFunkyDutchDate(DateTime this theDate) {
var result = string.Format("{0:dd-MM-yyyy}", theDate);
return result;
}
In similar trivial cases I could even tend to return the formatted string immediately. But this is just a simple example, because in a little more complex functions I often use this 'trick' of assigning the result to a temporary local variable first.
My main reason for this is that this allows easier debugging. I can just put a breakpoint on the return result;
line, run and inspect if the result my function came up with is correct.
But the extra temporary result
variable still feels a bit like unperformant then the alternative without:"
public static string ToFunkyDutchDate(DateTime this theDate) {
return string.Format("{0:dd-MM-yyyy}", theDate);
}
I have eased this nagging feeling in three ways:
- Any performance decrease would be negligable
- Having a variable like
result
makes the code a bit more legible thenreturn very long multi-line expression
, which is worse any performance decrease - If C-sharp's compiler was anywhere decent - which I think it is - then it SHOULD compile the extra variable away. E.g. make the resultant bytecode the exact same as if the function just returned the calculated result immediately without using a temporary variable. Either immediately (when not running in debug mode) - or perhaps when doing an optimized/production build (
/optimize+
).
But I've done this for so many years now, on so many lines of code, I thought I'd just finally ask it. Any compiler wizards here that know? :)
Edit: An answer within a minute to a question that had simmered for years. How great is Stackoverflow. Great tool: http://tryroslyn.azurewebsites.net/