I would like to know if there are any significant disadvantages to creating a temporary variable for a value that is accessed multiple times within a small scope.
eg:
filep->waypt[rp->leg[j]].ID
or
(*(filep->route + filep->nroutes - 1))->number
These are examples from a recent project where I forced myself to avoid almost any simplification for variable references in order to improve my skills with C pointers (it was painful). However, the habit seemed to stick. I find that the more I try to introduce variables to simplify my code (readability and typing volume) the more confusing it becomes to remember exactly what each new variable references.
I’ve only ever had my code reviewed in an educational setting, and I would like to know what others find easier to digest and where are the performance tradeoffs (if any).
When would assigning a value who’s memory address would require several arithmetic operations to calculate it’s own variable start to cause performance issues? Would it make a difference if done once in a loop? What about once in a nested loop? What about a value assigned to it’s own variable in a loop, but is then accessed in an inner loop?
How would this change in an interpreted language?
Say in PHP (please excuse syntactical errors, I’m new to PHP):
$employees[$i][$phone]['Home']['number'];
vs
$home = $employees[$i][$phone]['Home']['number'];
And finally, if it’s not too subjective (code readability shouldn’t be!), which is considered the best practice for writing readable code? I write code that is as self-documenting as possible, but if variables begin to get too contrived and are referenced multiple times, I will assign them their own variable. However, the reason this works for me could be that I’ve gotten used to my own style.
There’s a fairly good chance that any decent compiler will detect common sub-expressions and optimise them for you.
However, I would still opt for a temporary variable if it improved the readability of my code, despite the fact that it introduced extra storage (though minimal).
I consider maintainability of code far more important than a tiny storage hit. By way of (contrived) example, I would probably replace a whole lot of:
calls with:
As to interpreted languages, I have less information on that. I know quite a bit about how to optimise assembly code (though nowhere near as much as the demigods that write compilers, which is why I normally leave it to them). I know somewhat less about the virtual machines running inside most interpreters.
But I would still code for readability. I don’t want to see a bucketload of
$employees[$i][$phone]['Home']['number']snippets stuck in my code. I would rather addin there somewhere and just use
$homePhonefrom that point onward.