Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
188 views
Welcome To Ask or Share your Answers For Others

1 Answer

It depends on what foo.getLength() does. If it can be inlined, it can be effectively the same thing. If it cannot be inlined, the JVM cannot determine whether the result is the same.

BTW you can write for a one liner.

for(int i = 0, length = foo.getLength(); i < length; i++){   }

EDIT: It is worth nothing that;

  • methods and loops are usually not optimised until they have been called 10,000 times.
  • profilers sub-sample invocations to reduce overhead. They might count every 10 or 100 or more so a trivial example may not show up.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...