如果我在循环中多次调用代码,哪种最快的解决方案会更好?
int length = 4;
int firstIndex = 4;
int lastIndex = 7;
int currIndex = 4;
// Example 1 (if statement)
// Incrementing currIndex
if (++currIndex > lastIndex)
currIndex = firstIndex;
// Decrementing currIndex
if (--currIndex < firstIndex)
currIndex = lastIndex
// Example 2 (Modulo)
// Incrementing currIndex
currIndex = firstIndex + (++currIndex % length);
// Decrementing currIndex
currIndex = firstIndex + ((--currIndex + length) % length);
最佳答案
它们可能非常接近,在实践中并不重要。如果您确实想找到答案,请将每种方法包装在一个循环中,执行 100,000 或 1M 次并计时。
我的猜测是“if”语句会更快。它只有一个加法,以及一对比较和分支语句,这些语句是处理器中的“廉价”指令。模数至少需要同样多的语句,但成本更高。
关于java - 速度模或 if 语句哪个更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37191099/