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

前端 未结 6 1275
不知归路
不知归路 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:44

    Are you trying to find out if doing the assignment each loop is faster in total run time than doing a check each loop and only assigning once on satisfaction of the test condition?

    In the above example I would guess that the first is faster. You perform 5 assignments. In the latter you perform 5 test and then an assignment.

    But you'll need to up the iteration count and throw in some stopwatch timers to know for sure.

提交回复
热议问题