简体   繁体   English

性能:else if vs if在函数中已经返回

[英]Performance: else if vs if in function that already returned

Is there any difference in performance between using else if / if in a function that returns something? 在返回内容的函数中使用else if / if之间的性能是否有区别? I mean, if the function already returned, it won't execute the next if anyways, which is the purpose of else if, right? 我的意思是,如果该函数已经返回,则无论如何都不会执行下一个,这是其他if的目的,对吗? I wrote a small code snippet to illustrate that 我写了一个小代码段来说明

#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;
}

it should all be the same, one way to check for better performace is to compare your assembly code, you can use tools like godbolt.org, usually the code that generates fewer instructions performs faster. 都应该是相同的,一种检查性能更好的方法是比较汇编代码,可以使用Godbolt.org之类的工具,通常生成较少指令的代码执行速度更快。

by the way, it is better if you compare for "return 0" before the other two cases, as almost 100% of the times your input argument is not 3 or 4, 顺便说一句,最好在其他两种情况之前比较“返回0”,因为几乎100%的输入参数不是3或4,

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

is much better than

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM