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

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

    Relative to your barebones example (and perhaps your real application):

    boolean b = false;
    // .. other stuff, might change b
    int i = 0;
    // .. other stuff, might change i
    b |= i < 5;
    while(i++ < 5) {
        // .. stuff with i, possibly stuff with b, but no assignment to b
    }
    

    problem solved?

    But really - it's going to be a question of the cost of your test (generally more than just if (boolean)) and the cost of your assignment (generally more than just primitive = x). If the test/assignment is expensive or your loop is long enough or you have high enough performance demands, you might want to break it into two parts - but all of those criteria require that you test how things perform. Of course, if your requirements are more demanding (say, b can flip back and forth), you might require a more complex solution.

提交回复
热议问题