就性能和逻辑而言,嵌套的if(条件)和逻辑运算符之间有何区别?
if(a && b && c){
//do something
}
if(a){
if(b){
if(c){
//do something
}
}
}
以上代码在逻辑上是否相同? 我主要关心的是代码的性能,明智的使用哪种才是最好的?
答案 0 :(得分:0)
如果您尝试将这两个代码转换为assembly
语言(与机器语言非常接近),则两个代码将转换为完全相同的语言(first code,second code):< / p>
C :
void Main(){
int a=1, b=2, c= 3, res = 0;
if(a && b && c)
res = 100;
}
// or
void Main(){
int a=1, b=2, c= 3, res = 0;
if(a)
if(b)
if(c)
res = 100;
}
组装输出:
Main():
push rbp
mov rbp, rsp
mov DWORD PTR [rbp-4], 1
mov DWORD PTR [rbp-8], 2
mov DWORD PTR [rbp-12], 3
mov DWORD PTR [rbp-16], 0
cmp DWORD PTR [rbp-4], 0
je .L3 ; jump to the end if `a` is not true
cmp DWORD PTR [rbp-8], 0
je .L3 ; jump to the end if `b` is not true
cmp DWORD PTR [rbp-12], 0
je .L3 ; jump to the end if `c` is not true
mov DWORD PTR [rbp-16], 100 ; otherwise do something
.L3:
nop
pop rbp
ret