【发布时间】:2021-07-21 08:15:41
【问题描述】:
这个问题更多的是理论问题而不是实际问题,仅考虑多个if 与链式if else 的性能。让我们抛开switch、可读性、微优化、错误减少等问题。
假设我有以下构造:
if( i == 1 ){
// Do one thing
}
else if( i == 2 ){
// Do another thing
}
else if( i == 3 ){
// Do a third thing
}
// ... and so on
我一直认为执行起来会比以下更有效:
if( i == 1 ){
// Do one thing
}
if( i == 2 ){
// Do another thing
}
if( i == 3 ){
// Do a third thing
}
// ... and so on
但在现代编译器中真的如此吗?据我了解,现在的编译器在这些类型的结构上使用了很多优化和分支策略,所以也许它们实际上都会产生相同的可执行代码?
【问题讨论】:
标签: if-statement compiler-optimization