package jdk.test; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.infra.Blackhole; import java.util.concurrent.ThreadLocalRandom; public class HashBench { private static final char[] buf; static { buf = new char[128]; for (int i = 0; i < buf.length; i++) { buf[i] = (char) ThreadLocalRandom.current().nextInt(1 << 16); } } private static final String master = new String(buf); @Benchmark public void hashCode(Blackhole bh) { bh.consume(new String(master).hashCode()); } @Benchmark public void hashCode0(Blackhole bh) { int h = 0; for (char c : buf) { h = h * 31 + c; } bh.consume(h); } @Benchmark public void hashCode1(Blackhole bh) { int h = 0; int i0 = 0; int i1 = 1; while (i1 < buf.length) { h = h * (31 * 31) + buf[i0] * 31 + buf[i1]; i0 = i1 + 1; i1 = i0 + 1; } if (i0 < buf.length) { h = h * 31 + buf[i0]; } bh.consume(h); } @Benchmark public void hashCode2(Blackhole bh) { int h = 0; int i0 = 0; int i1 = 1; int i2 = 2; while (i2 < buf.length) { h = h * (31 * 31 * 31) + buf[i0] * (31 * 31) + buf[i1] * 31 + buf[i2]; i0 = i2 + 1; i1 = i0 + 1; i2 = i1 + 1; } if (i0 < buf.length) { h = h * 31 + buf[i0]; } if (i1 < buf.length) { h = h * 31 + buf[i1]; } bh.consume(h); } @Benchmark public void hashCode3(Blackhole bh) { int h = 0; int i0 = 0; int i1 = 1; int i2 = 2; int i3 = 3; while (i3 < buf.length) { h = h * (31 * 31 * 31 * 31) + buf[i0] * (31 * 31 * 31) + buf[i1] * (31 * 31) + buf[i2] * 31 + buf[i3]; i0 = i3 + 1; i1 = i0 + 1; i2 = i1 + 1; i3 = i2 + 1; } if (i0 < buf.length) { h = h * 31 + buf[i0]; } if (i1 < buf.length) { h = h * 31 + buf[i1]; } if (i2 < buf.length) { h = h * 31 + buf[i2]; } bh.consume(h); } @Benchmark public void hashCode3x(Blackhole bh) { int h = 0; int i0 = 0; int i1 = 1; int i2 = 2; int i3 = 3; while (i3 < buf.length) { h = (((((h * 31 + buf[i0]) * 31) + buf[i1]) * 31) + buf[i2]) * 31 + buf[i3]; i0 = i3 + 1; i1 = i0 + 1; i2 = i1 + 1; i3 = i2 + 1; } if (i0 < buf.length) { h = h * 31 + buf[i0]; } if (i1 < buf.length) { h = h * 31 + buf[i1]; } if (i2 < buf.length) { h = h * 31 + buf[i2]; } bh.consume(h); } }