的计算成本是否有差异
if(something){
return something;
}else{
return somethingElse;
}
和
if(something){
return something;
}
//else (put in comments for readibility purposes)
return somethingElse;
从理论上讲,我们有命令(其他),但似乎并没有什么实际的区别。
编辑:在为不同的集合大小运行代码后,我发现实际上存在差异,没有其他代码的效率似乎提高了1.5%。但这很可能取决于编译器,如以下许多人所述。我测试过的代码:
int withoutElse(bool a){
if(a)
return 0;
return 1;
}
int withElse(bool a){
if(a)
return 0;
else
return 1;
}
int main(){
using namespace std;
bool a=true;
clock_t begin,end;
begin= clock();
for(__int64 i=0;i<1000000000;i++){
a=!a;
withElse(a);
}
end = clock();
cout<<end-begin<<endl;
begin= clock();
for(__int64 i=0;i<1000000000;i++){
a=!a;
withoutElse(a);
}
end = clock();
cout<<end-begin<<endl;
return 0;
}
检查了从1000000到1000000000000的循环,结果始终是不同的
编辑2:汇编代码(再次使用Visual Studio 2010生成)也显示出很小的差异(显然,我对汇编器:()不好
?withElse@@YAH_N@Z PROC ; withElse, COMDAT
; Line 12
push ebp
mov ebp, esp
sub esp, 192 ; 000000c0H
push ebx
push esi
push edi
lea edi, DWORD PTR [ebp-192]
mov ecx, 48 ; 00000030H
mov eax, -858993460 ; ccccccccH
rep stosd
; Line 13
movzx eax, BYTE PTR _a$[ebp]
test eax, eax
je SHORT $LN2@withElse
; Line 14
xor eax, eax
jmp SHORT $LN3@withElse
; Line 15
jmp SHORT $LN3@withElse
$LN2@withElse:
; Line 16
mov eax, 1
$LN3@withElse:
; Line 17
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret 0
?withElse@@YAH_N@Z ENDP ; withElse
和
?withoutElse@@YAH_N@Z PROC ; withoutElse, COMDAT
; Line 4
push ebp
mov ebp, esp
sub esp, 192 ; 000000c0H
push ebx
push esi
push edi
lea edi, DWORD PTR [ebp-192]
mov ecx, 48 ; 00000030H
mov eax, -858993460 ; ccccccccH
rep stosd
; Line 5
movzx eax, BYTE PTR _a$[ebp]
test eax, eax
je SHORT $LN1@withoutEls
; Line 6
xor eax, eax
jmp SHORT $LN2@withoutEls
$LN1@withoutEls:
; Line 7
mov eax, 1
$LN2@withoutEls:
; Line 9
pop edi
pop esi
pop ebx
mov esp, ebp
pop ebp
ret 0
?withoutElse@@YAH_N@Z ENDP ; withoutElse
它通常有所不同,但是编译器可能会决定在两种情况下都执行相同的跳转(实际上,它总是会执行此操作)。查看编译器工作的最佳方法是读取汇编器。假设您正在使用gcc,可以尝试
gcc -g -c -fverbose-asm myfile.c; objdump -d -M intel -S myfile.o > myfile.s
这将混合使用汇编程序/ c代码,并从一开始就使工作变得更加容易。
至于你的例子是:
情况1
if(something){
23: 83 7d fc 00 cmp DWORD PTR [ebp-0x4],0x0
27: 74 05 je 2e <main+0x19>
return something;
29: 8b 45 fc mov eax,DWORD PTR [ebp-0x4]
2c: eb 05 jmp 33 <main+0x1e>
}else{
return 0;
2e: b8 00 00 00 00 mov eax,0x0
}
案例2
if(something){
23: 83 7d fc 00 cmp DWORD PTR [ebp-0x4],0x0
27: 74 05 je 2e <main+0x19>
return something;
29: 8b 45 fc mov eax,DWORD PTR [ebp-0x4]
2c: eb 05 jmp 33 <main+0x1e>
return 0;
2e: b8 00 00 00 00 mov eax,0x0
您可以想象没有任何区别!
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句