Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is bitwise operation faster than modulo/reminder operator in 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;
    }
}

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?

Thanks, Niranjan

like image 781
Niranjan Avatar asked Feb 19 '14 19:02

Niranjan


1 Answers

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.)

like image 89
Richard Wilkes Avatar answered Sep 19 '22 16:09

Richard Wilkes