3 ms·
Saving the array length to a variable is one of those things that inexperienced programmers love to do, thinking it will optimise something.
by laurent123456 7y ago
Saving the array length to a variable is one of those things that inexperienced programmers love to do, thinking it will optimise something.
- vips7L 7y agoIt honestly depends on the compiler.
- stult 7y agoIt's a great default assumption when you don't know all the quirks of the specific language or compiler, because either it will help you or at least won't hurt you.
- laurent123456 7y agoIt might hurt if you add this extra variable to every loop and at some point the array length changes within the loop. It also makes the code more verbose. This optimisation should be done like all optimisations: first you benchmark and then see if it makes sense to make this change. Most of the time there's no point doing so.
- ajnin 7y agoAvoiding doing unnecessary work is something all developers should strive to, experienced or not. Maybe in that case that won't make any difference. But, say, a method call in a loop often sould be done outside the loop. Doing it here but not there leads to inconsistent style. Also depending on the language and compiler that might actually make a difference sometimes. I'm not going to write code that assumes a certain interpreter/compiler behavior.