What's the best practice?
This :
for ($i = 0; $i < count($array); $i++) {
//stuff
}
Or, what I usually do :
$count = count($array);
for($i = 0; $i < $count; $i++) {
//stuff
}
Is it the same with the magic of compiler optimization?
Profile and see it yourself. In general, the first sample will execute But:
For example, in C#, using a A rule of thumb:
| ||||
|
it depends on whether The first variant is more explicit since you can directly see that the length of the array is the limit of the loop, it could be slightly slower than the second, but in interpreted languages this should not be too much of a problem. | |||||||||||||
|
The particular optimization in question goes by a couple of names typically hoisting or loop invariant code motion. It is a fairly common optimization performed by compilers. If you are in a compiled language don't worry about it, it is probably taken care of. If you are in an interpreted language then weather or not it happens is less certain. | ||||
|
Most languages allow you to initialize multiple variables during the declaration of a This is true in C++, C#, Java and PHP. Now, in the last example let's assume the function There are two common practices to solve this problem.
And
I prefer the second as it's easier to read what $x does, and what it's used for. EDIT: To answer the question, if compiler optimization takes place. The answer is No. All compilers that I've seen will continue to evaluate the condition statement of a for loop for each iteration. If that condition contains a function call such as | |||||
|
count()
always returns the same value, and the compiler doesn't always know that. – Blrfl May 17 at 22:35