c++ - 哪个条件语句比另一个更快 (width*height*depth == 0) OR (width ==0 || height == 0 || depth == 0)
问题描述
在计算速度很重要的算法中描述 3 维对象时,以下哪个条件表达式更快?
class Box {
unsigned int width, height, depth;
public:
bool isNull(){
return (width*height*depth == 0);
//OR
return (width ==0 || height == 0 || depth == 0);
}
};
解决方案
return 语句中使用的表达式
return (width*height*depth == 0);
通常只是相对于第二个 return 语句中的表达式不正确。由于溢出,您可以获得等于 0 的结果,但这并不意味着其中一个操作数等于 0。
这是一个演示程序。
#include <iostream>
int main()
{
std::cout << 0x10000000u * 0x10000000u * 10u << '\n';
return 0;
}
程序输出为
0
尽管两个操作数都不等于0
。
推荐阅读
- postgresql - Indexing a jsonb array in Postgres
- java - 如何创建从内存到数据库的后写缓存?
- c# - Avoid OnResultExecuted Filter on ASP.NET MVC 5 application's Action
- python - 创建上下文后获取python守护进程pid
- ruby-on-rails - Rails 上的 select_tag 中的 ArgumentError
- vba - 处理项目后重新选择日历中的项目
- python - 将 websocket 用于 python 网络爬虫——rsv 尚未实现
- php - OVH CRON:如何执行 Symfony 命令?
- typescript - Typescript extensions. Conditional Types
- linux - 在记录过程运行时清除日志文件