0

I was doing a bit manipulation problem the other day, and realized I could replace n % 16 with n & 15

Since % is slow, and & fast, is this a good optimization, or does the compiler already do something like this, and I don't need to bother?

Qrow Saki
  • 932
  • 8
  • 19
  • 1
    Most compilers *tend* to do this kind of optimization for you. In the case of Java, the optimization won't happen in the compiler (i.e. the thing that converts `.java` files to `.class` files), but at runtime. If you want to benchmark it yourself check out [this question on menchmarking](https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java). – Joachim Sauer Aug 13 '21 at 16:15
  • Do you do this operation millions of times per second or once every few seconds? – luk2302 Aug 13 '21 at 16:16
  • And... I'm not sure you can assume that the % operator is less efficient than the &. – Mark Lavin Aug 13 '21 at 16:18
  • 3
    Replacing `n % 16` with `n & 15` for performance reasons is premature optimization. As the source code of the hotspot assembler shows (https://github.com/openjdk/jdk11u/blob/master/src/hotspot/cpu/x86/c1_LIRAssembler_x86.cpp#L2569) it is the Java runtime that does this optimization for a constant divisor that is a power of two anyway. – Thomas Kläger Aug 13 '21 at 16:45

1 Answers1

0

There is a very tricky difference here. The same idea that you have here is sort of done when choosing a bucket in the HashMap implementation.

If your n is negative:

System.out.println(-31 % 16); // -15
System.out.println(-31 & 15); // 1

you will get different results.

Eugene
  • 117,005
  • 15
  • 201
  • 306