Java for loop vs. while loop. Performance difference?

前端 未结 16 1579
长发绾君心
长发绾君心 2020-11-28 09:35

Assume i have the following code, there are three for loop to do something. Would it run fast if i change the most outer for loop to while loop? thanks~~

<         


        
相关标签:
16条回答
  • 2020-11-28 10:25

    Did anyone tried like this...

    int i = 20;
    while (--i > -1){
        // do stuff
    }
    

    Compared to:

    for (int i = 0; i < 20; i++){
        // do Stuff
    }
    
    0 讨论(0)
  • 2020-11-28 10:28

    No, you're still looping the exact same number of times. Wouldn't matter at all.

    0 讨论(0)
  • 2020-11-28 10:28

    Based on this: https://jsperf.com/loops-analyze (not created by me) the while loop is 22% slower than a for loop in general. At least in Javascript it is.

    0 讨论(0)
  • 2020-11-28 10:32

    No, it's not going to make a big difference, the only thing is that if your nesting loops you might want to consider switching up for example for organizational purposes, you may want to use while loop in the outer and have for statements inside it. This wouldn't affect the performance but it would just make your code look cleaner/organized

    0 讨论(0)
  • 2020-11-28 10:33

    here's a helpful link to an article on the matter

    according to it, the While and For are almost twice as faster but both are the same.

    BUT this article was written in 2009 and so i tried it on my machine and here are the results:

    • using java 1.7: the Iterator was about 20%-30% faster than For and While (which were still the same)
    • using java 1.6: the Iterator was about 5% faster than For and While (which were still the same)

    so i guess the best thing is to just time it on your own version and machine and conclude from that

    0 讨论(0)
  • 2020-11-28 10:33

    Look at your algorithm! Do you know beforehand which values from your array are added more than one time?

    If you know that you could reduce the number of loops and that would result in better performance.

    0 讨论(0)
提交回复
热议问题