|
![](/i/fill.gif) |
Warp wrote:
> Daniel Nilsson <pov### [at] daniel-nilsson com> wrote:
>> The thing to learn from this, and it's my experience from work too, is
>> that you should write code that is easy to read and maintain rather than
>> try to be clever with optimizations.
>
> IMO this:
>
> variable = someLengthyCalculation;
> useVariable(variable);
> useVariableForSomethingElse(variable);
>
> is more readable than:
>
> useVariable(someLengthCalculation);
> useVariableForSomethingElse(someLengthCalculation);
>
> especially if "someLengtyCalculation" is even a bit complicated. (Basically
> the variable makes it very clear that the two expressions are, in fact, the
> one and same, something which might not be visually obvious if the expression
> is repeated.)
>
> As a bonus, you'll make absolutely sure the compiler won't calculate
> it twice. (In some cases it might be that the compiler is forced to
> calculate it twice because it can't know if some called function has
> side-effects.)
>
Yes, I agree that in this case the code with the variable is the most
readable. My point is that in general you should not bother with
optimization. The compiler is most of the time clever enough to figure
it out. Only try to optimize if profiling shows some inefficiency.
--
Daniel Nilsson
Post a reply to this message
|
![](/i/fill.gif) |