0

I have been following Modulus for Mersenne's Prime and written following two methods:

First Method :

mersneMod(int x){
  while(x > 7){
    x = (x & 7) + (x >> 3);
  }
 return x == 7 ? 0 : x;
}

Second Method:

mod(int x){
  return x % 7;
}

When I bench mark these two method against numbers from 0 to 9000000 I get following numbers:

Method 1 : 65784647 ns
Method 2 : 2901699 ns

So far, I have been thinking method 1 should be faster but it is not. Can anyone explain what's going on inside % operator of java. Thanks!

Amit Kumar
  • 2,685
  • 2
  • 37
  • 72
  • 2
    Why do you think method 1 should be faster than method 2? – Jesper Dec 06 '17 at 12:35
  • 2
    Step A) compare byte code ... step B) you read and understand https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java ... and you are sure that your numbers are really meaningful? – GhostCat Dec 06 '17 at 12:36
  • 2
    fast analysis: 3 lines of code vs. 1 line of code; 2 conditionals and 3 operations against 1 operation; a loop vs. a single simple statement - at least 3 hints that method 1 should **not** be faster. – user85421 Dec 06 '17 at 12:54

0 Answers0