1

众所周知,有一种享受可以得到余数:

m = 余数

n = 数量

d = 除数,一个正整数

米 = n & ( d - 1 )

它适用于 d = 2^k(k 是正整数)

对于 JDK 12,我使用 jmh 来测试效率:

@State(Scope.Thread)
public static class Generator {
    SequentialGenerator sequentialGenerator = new SequentialGenerator(1, Integer.MAX_VALUE);
    SequentialGenerator powerGenerator = new SequentialGenerator(1, 17);
}

@Benchmark
@Warmup(iterations = 1)
@Measurement(iterations = 120)
public void mod2_1(Generator generator) {

    int pow = generator.powerGenerator.nextValue().intValue();
    int factor = 1 << pow;
    int i = generator.sequentialGenerator.nextValue().intValue();

    for (long j = 0; j < 1000L; j++) {
        int k = i & (factor -1);
    }
}

@Benchmark
@Warmup(iterations = 1)
@Measurement(iterations = 120)
public void mod2_2(Generator generator) {

    int pow = generator.powerGenerator.nextValue().intValue();
    int factor = 1 << pow;
    int i = generator.sequentialGenerator.nextValue().intValue();

    for (long j = 0; j < 1000L; j++) {
        int k = i % factor;
    }
}

结果表明 % 比 & 更有效,为什么:

Benchmark                 Mode  Cnt        Score       Error  Units
BitUtilTest.mod2_1       thrpt  120  1218565.022 ± 32816.798  ops/s
BitUtilTest.mod2_2       thrpt  120  2045390.684 ± 56090.355  ops/s
4

0 回答 0