c++ - 性能:else if vs if 在已经返回的函数中

标签 c++ performance

在返回值的函数中使用 else if/if 在性能上有什么不同吗?我的意思是,如果函数已经返回,它不会执行下一个 if,这就是 else if 的目的,对吧?我写了一个小代码片段来说明这一点

#include <iostream>

bool foo(int x)
{
if (x == 3) return 1;
else if (x == 4) return 1; //using only if here has the performance of else if?
return 0;
}

int main()
{
int x = 4;
std::cout << foo(x);
std::cin.get();
return 0;
}

最佳答案

应该都是一样的,检查性能更好的一种方法是比较你的汇编代码,你可以使用像 godbolt.org 这样的工具,通常生成更少指令的代码执行得更快。

顺便说一下,如果你在其他两种情况之前比较“return 0”会更好,因为几乎 100% 的时间你的输入参数不是 3 或 4,

if (x != 3) return 0;
return 1;

好多了
if (x == 3) return 1; 
return 0;

关于c++ - 性能:else if vs if 在已经返回的函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49713340/

相关文章:

c++ - 异常安全 - 可靠回滚对象状态的模式

c++ - 为 C++ Windows 服务动态创建安装程序

Java JasperReport 非常慢

performance - F#中的返回字符串和代码优化

c++ - 通过引用返回 unique_ptr 的 vector

c++ - 如何创建一个新类来继承 ostream 并将其用作 cout 但带有锁

c# - Dapper 性能结果在我的机器上看起来非常相似

java - 许多图形组件以何种方式影响 Swing GUI 的性能?

C++11 强制转换const迭代器指向shared_ptr对象的容器

jquery - 如何在jsp中创建搜索文本框?