[英]Is it bad to execute if(false) many times?
If I have a piece of code like so... 如果我有一段这样的代码......
if(!hasRunMethod) {
runMethod();
hasRunMethod = true;
}
...and that code is being executed in a loop over and over, many times every second, even though the code inside is only called once, is this bad coding practice? ...并且该代码正在循环中执行,每秒多次,即使内部代码只被调用一次,这是不好的编码实践? If so, what should I do instead?
如果是这样,我该怎么做呢?
Quickly tested (on java version 1.8.0_05): 快速测试(在java版本1.8.0_05上):
long start = System.nanoTime();
int run = 1_000_000;
for(int i = 0; i < run; ++i) {
if(alwaysTrue) {
}
}
long end = System.nanoTime();
end - start
averages ~1,820,000 nano seconds. end - start
平均约1,820,000纳秒。 this: 这个:
long start = System.nanoTime();
int run = 1_000_000;
for(int i = 0; i < run; ++i) {
// if(alwaysTrue) {
//
// }
}
long end = System.nanoTime();
end - start
averages ~1,556,000 nano seconds. end - start
平均值~1556,000纳秒。
as an added bonus: 作为额外奖励:
long start = System.nanoTime();
int run = 1_000_000;
for(int i = 0; i < run; ++i) {
if(true) {
}
}
long end = System.nanoTime();
end - start
averages ~1,542,000 nano seconds, same as commented out. end - start
平均值~1542,000纳秒,与评论相同。
if(someBool){}
inside a loop has some performance impact. if(someBool){}
在循环中有一些性能影响。 But it's so negligible I find it hard to think of a bottleneck sensitive enough for it to matter. 但它是如此微不足道,我发现很难想到一个足够敏感的瓶颈让它变得重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.