循环时哪个成本更高;赋值或if语句? [英] Which costs more while looping; assignment or an if-statement?
问题描述
考虑以下两种情况:
boolean b = false;
int i = 0;
while(i++ < 5) {
b = true;
}
或
boolean b = false;
int i = 0;
while(i++ < 5) {
if(!b) {
b = true;
}
}
哪个更昂贵"?如果答案取决于使用的语言/编译器,请提供.我的主要编程语言是 Java.
Which is more "costly" to do? If the answer depends on used language/compiler, please provide. My main programming language is Java.
请不要问我为什么要这样做之类的问题.它们只是指出相关问题的准系统示例:是否应该在循环中一遍又一遍地为变量设置相同的值,或者是否应该对其进行测试在每个循环中,它都持有一个需要更改的值?
Please do not ask questions like why would I want to do either.. They're just barebone examples that point out the relevant: should a variable be set the same value in a loop over and over again or should it be tested on every loop that it holds a value needed to change?
推荐答案
请不要忘记 Optimization Club 的规则.
- Optimization Club 的第一条规则是,您不要进行优化.
- Optimization Club 的第二条规则是,没有衡量就不要优化.
- 如果您的应用运行速度快于底层传输协议,则优化就结束了.
- 一次一个因素.
- 没有市场,没有市场时间表.
- 测试将继续进行.
- 如果这是您在 Optimization Club 的第一个晚上,您必须编写一个测试用例.
您似乎违反了规则 2.您没有衡量标准.如果您真的想知道,您将通过设置一个测试来回答这个问题,该测试针对场景 B 运行场景 A 并找到答案.不同环境之间有很多差异,我们无法回答.
It seems that you have broken rule 2. You have no measurement. If you really want to know, you'll answer the question yourself by setting up a test that runs scenario A against scenario B and finds the answer. There are so many differences between different environments, we can't answer.
这篇关于循环时哪个成本更高;赋值或if语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!