Say I have a simple PHP loop like this one
// Bad example
$array = array('apple','banana','cucumber');
for ($i = 1; $i < count($array); $i++) {
echo $array[$i];
}
I know this is a bad practice. It’s better not using count() inside a loop.
// Nice example
$array = array('apple','banana','cucumber');
$limit = count($array);
for ($i = 1; $i < $limit; $i++) {
// do something...
}
In Java, I would do it this way
// Bad example?
String[] array = {"apple","banana","cucumber"};
for(int i = 0; i < array.length; i++){
System.out.println(array[i]);
}
Question: Isn’t this above a bad practice too? Or it is just the same as the example below?
// Nice example?
String[] array = {"apple","banana","cucumber"};
int limit = array.length;
for(int i = 0; i < limit; i++){
System.out.println(array[i]);
}
The “bad” examples you use are not equivalent, and thus are not comparable – even if they seem so on the surface. Using this description:
(which is descriptive of both PHP and java loops), the initialization statement is executed once, at the start of the loop. The termination statement and the increment are executed for each iteration of the loop.
The reason it is bad practice to use PHP’s
countin the termination statement is that, for each iteration, thecountfunction call occurs. In your Java example,array.lengthis not a function call but a reference to a public member. Therefore, the termination statements used in your examples are not equivalent behavior. We expect a function call to be more costly than a property reference.It is bad practice to place a function call (or call a property that masks a function) in the termination statement of a for loop in any language which has the described loop mechanics. That’s what makes the PHP example “bad”, and it would be equally bad if you used a
count-type function in Java for loop’s termination statement. The real question, then, is whether Java’sArray.lengthdoes indeed mask a function call – the answer to that is “no” (see the potential duplicate question, and/or check out http://leepoint.net/notes-java/data/arrays/arrays.html)