Which costs more while looping; assignment or an if-statement?

前端 未结 6 1264
不知归路
不知归路 2020-12-29 06:04

Consider the following 2 scenarios:

boolean b = false;
int i = 0;
while(i++ < 5) {
    b = true;
}

OR

boolean b = false;         


        
6条回答
  •  感情败类
    2020-12-29 06:24

    Have you tested this? Working on a Linux system, I put your first example in a file called LoopTestNoIf.java and your second in a file called LoopTestWithIf.java, wrapped a main function and class around each of them, compiled, and then ran with this bash script:

    #!/bin/bash
    function run_test {
      iter=0
      while [ $iter -lt 100 ]
      do
        java $1
        let iter=iter+1
      done
    }
    time run_test LoopTestNoIf
    time run_test LoopTestWithIf
    

    The results were:

    real    0m10.358s 
    user    0m4.349s 
    sys     0m1.159s 
    
    real    0m10.339s
    user    0m4.299s 
    sys     0m1.178s
    

    Showing that having the if makes it slight faster on my system.

提交回复
热议问题