lundi 22 décembre 2014

readability vs shorter code in returning from function


In something as simple as



int sq(int x) { int y = x*x; return y; }


versus



int sq(int x) { return (x*x); }


the former function requires an extra IL step.


EDIT: IL code from the first example, using the current C# compiler from VS 2013 Update 4 (.NET Framework 4.5.1), code from the optimized release version:



IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: mul
IL_0003: stloc.0 // These two instructions
IL_0004: ldloc.0 // seem to be unneccessary
IL_0005: ret


and from the second example:



IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: mul
IL_0003: ret


Is that IL extra step indicative of data being copied in memory? Is this difference still present when using something seemingly better optimized? (C?)


If yes to first or both: can I use the latter, especially when the returned data takes a lot of space, and presumably a lot of time to be moved in memory? Or should I favor the former, because it is more readable? LINQ makes it easy to have whole functions inside a long return() line, but my example faces the same choice were it C. Speed or readability?


In general, would you put the last bit of maths between the parentheses in the return line?





Aucun commentaire:

Enregistrer un commentaire