I've been told at school that it's a bad practice to modify the index variable of a for loop
:
Example :
for(int i = 0 ; i < limit ; i++){
if(something){
i+=2; //bad
}
if(something){
limit+=2; //bad
}
}
The argument was that some compiler optimization can optimize the loop and not recalculate the index and bound at each loop.
I 've made some test in java
and it seems that by default index and bound are recalculate each time.
I'm wondering if it's possible to activate this kind of feature in the JVM HotSpot
?
For example to optimize this kind of loop :
for(int i = 0 ; i < foo.getLength() ; i++){ }
without having to write :
int length = foo.getLength()
for(int i = 0 ; i < length ; i++){ }
It's just an example I'm curious to try and see the improvments.
EDIT
According to Peter Lawrey answer why in this simple example the JVM don't inline getLength()
method? :
public static void main(String[] args) {
Too t = new Too();
for(int j=0; j<t.getLength();j++){
}
}
class Too {
int l = 10;
public Too() {
}
public int getLength(){
//System.out.println("test");
return l;
}
}
In the output "test" is print 10 times.
I think it could be nice to optimize this kind of execution.
EDIT 2 : Seems I made a misunderstood...
I have remove the println
and indeed the profiler tell me that the method getLength()
is not even call once in this case.
println()
call. Also you really shouldn't worry about such compiler optimizations - or if you do, you have to understand at least enough to know how to test this kind of code. – RufenagetLength()
just fine, independent whether you have println() statement in there or not. If you want the details I posted a short summary below ;) – Rufena