问题描述
我在几篇博客中读到,在Java模数/提醒运算符中,运算符比按位与运算符慢.因此,我编写了以下程序进行测试.
I read in couple of blogs that in Java modulo/reminder operator is slower than bitwise-AND. So, I wrote the following program to test.
public class ModuloTest {
public static void main(String[] args) {
final int size = 1024;
int index = 0;
long start = System.nanoTime();
for(int i = 0; i < Integer.MAX_VALUE; i++) {
getNextIndex(size, i);
}
long end = System.nanoTime();
System.out.println("Time taken by Modulo (%) operator --> " + (end - start) + "ns.");
start = System.nanoTime();
final int shiftFactor = size - 1;
for(int i = 0; i < Integer.MAX_VALUE; i++) {
getNextIndexBitwise(shiftFactor, i);
}
end = System.nanoTime();
System.out.println("Time taken by bitwise AND --> " + (end - start) + "ns.");
}
private static int getNextIndex(int size, int nextInt) {
return nextInt % size;
}
private static int getNextIndexBitwise(int size, int nextInt) {
return nextInt & size;
}
}
但是在我的运行时环境(MacBook Pro 2.9GHz i7、8GB RAM,JDK 1.7.0_51)中,我看到的却不是.按位与运算要慢得多,实际上比其余运算符慢两倍.
But in my runtime environment (MacBook Pro 2.9GHz i7, 8GB RAM, JDK 1.7.0_51) I am seeing otherwise. The bitwise-AND is significantly slower, in fact twice as slow than the remainder operator.
如果有人可以帮助我了解这是故意的行为还是我做错了事,我将不胜感激.
I would appreciate it if someone can help me understand if this is intended behavior or I am doing something wrong?
谢谢,尼兰詹
推荐答案
您的代码按位报告-并且在我尝试过的每台Mac上,使用Java 6和Java 7的速度都更快.您机器上的测试恰巧与系统上的其他活动一致.您应该尝试多次运行测试,以验证您没有看到基于此的失真. (我本该将其作为评论"而不是答案",但是显然,您需要50名才能做到这一点-如果您问我,那真是愚蠢.)
Your code reports bitwise-and being much faster on each Mac I've tried it on, both with Java 6 and Java 7. I suspect the first portion of the test on your machine happened to coincide with other activity on the system. You should try running the test multiple times to verify you aren't seeing distortions based on that. (I would have left this as a 'comment' rather than an 'answer', but apparently you need 50 reputation to do that -- quite silly, if you ask me.)
这篇关于按位运算是否比Java中的模/提醒运算符快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!