【发布时间】:2016-07-24 02:05:35
【问题描述】:
如果我正在搜索一组值并为每个值运行代码,并且我想在找到某种质量时打开一个布尔值,然后在我为该对象运行代码时再次退出,运行条件检查是否需要关闭布尔值是否更快,或者在每个循环中简单地关闭它是否更快?
例如(伪代码):
bool found = false;
for(particle in literallyAHaystack) {
bool isNeedle = particle == "needle";
if(isNeedle) {
found = true;
}
// [some code that uses the 'found' variable]
if(isNeedle) {
found = false;
}
}
对
bool found = false;
for(particle in literallyAHaystack) {
bool isNeedle = particle == "needle";
if(isNeedle) {
found = true;
}
// [some code that uses the 'found' variable]
found = false; // a conditional no longer surrounds this statement
}
我知道这是非常低级且通常毫无意义的优化,但我仍然对它的真相感兴趣。我希望不要因为这个琐碎的问题而冒犯任何人。
【问题讨论】:
-
那么,呃...为什么你同时拥有
isNeedle和found?它们似乎是多余的。 -
@user2357112:我认为这个想法是想象
found可能由if中的某些内容设置,因此将整个内容编写为嵌套的if()子句而不使用布尔值来记录结果以前的检查需要重复代码。
标签: c optimization micro-optimization