if-else vs if performance
if-else vs if performance
假设我想要一个程序,它从任何设备输入一个数字,如果该数字为0,则返回-1,但在所有其他情况下继续执行该程序。
在c++中,部分代码将是:
int main() {
if(number == 0) return -1;
/*
Here the rest of the program
*/
return 0; // End of program
}
或
int main() {
if(number == 0) return -1;
else {
/*
Here the rest of the program
*/
}
return 0; // End of program
}
我的问题是,这些代码部分中哪一个更有效?
是的,我只讨论这种情况,当程序满足特定条件时,您需要退出程序
由于生成的代码完全相同,因此没有性能差异:
$ echo "int main() { int number; if (number == 0) return -1; return 0; }" | g++ -x c++ -S - -o /dev/stdout | md5sum
9430c430d1f748cc920af36420d160ce -
$ echo "int main() { int number; if (number == 0) return -1; else {} return 0; }" | g++ -x c++ -S - -o /dev/stdout | md5sum
9430c430d1f748cc920af36420d160ce -
$ echo "int main() { int number; if (number == 0) return -1; else {} return 0; }" | g++ -x c++ -S - -o /dev/stdout
.file ""
.text
.globl main
.type main, @function
main:
.LFB0:
.cfi_startproc
pushq %rbp
.cfi_def_cfa_offset 16
.cfi_offset 6, -16
movq %rsp, %rbp
.cfi_def_cfa_register 6
cmpl $0, -4(%rbp)
jne .L2
movl $-1, %eax
jmp .L3
.L2:
movl $0, %eax
.L3:
popq %rbp
.cfi_def_cfa 7, 8
ret
.cfi_endproc
.LFE0:
.size main, .-main
.ident "GCC: (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4"
.section .note.GNU-stack,"",@progbits
我看不出在效率方面有什么特别的不同。我认为第一个代码正在做同样的事情,并且不需要else
,因为如果输入是0
,编译器已经返回了-1
。
关闭编译器优化后,在某些情况下if比if-else更快。
这是因为在运行时可能的条件跳转少了一次。最好这样表示:
if(condition){
/*code*/
}
else{
//Jump 1
/*code*/
}
//Jump 2
Vs: if(conditional){
/*code*/
}
//Jump 1
/*code*/
在编译器优化的情况下,性能上应该没有什么区别,因为编译器会在可能的情况下为你做这些。如果可以的话,硬件上的分支预测也会尝试只使用其中一条语句,并且只有在使用其他选项时才会出现性能影响。
if-else语句用于决策,我想你已经知道了。
不要将整个程序或大部分程序写在else块中,因为如果if-else语句出错,将永远无法访问该代码。
if-else路由基本上是更好的,特别是当与else if一起使用时。它们都是有效的,但是使用括号(良好的实践/组织)
归根结底,它们是相同的语句,具有相同的效果,但这取决于您想要达到的目的。
就像我前面说的,不要在else块中编写程序的其余部分。如果这样,应用程序不能正常运行的风险会高得多。
if(number == 0)
{
return -1;
}
在您的示例中,该语句单独将是最佳路由。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何将enable-if与模板参数和参数包一起使用
- 无论条件是否为true,if总是在c++中执行
- Arduino:for/while/if在void setup()或void loop()之前?——错误:之前需要不合格
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 是否可以使用if constexpr删除控制流语句
- 要与"if constexpr"一起使用的编译时消息(在预处理器之后)
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- if数组上的随机数
- 将按位if条件转换为普通if条件
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 使用if-else将数字转换为单词
- 为什么简单的算术减法在"if"条件下不起作用?
- 以在Qt中的IF语句中设置时间延迟
- if-else vs if performance