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

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

    Any compiler (except, perhaps, in debug) will optimize both these statements to

    bool b = true;
    

    But generally, relative speed of assignment and branch depend on processor architecture, and not on compiler. A modern, super-scalar processor perform horribly on branches. A simple micro-controller uses roughly the same number of cycles per any instruction.

提交回复
热议问题