Are java.lang classes better served by the JVM?
Raffaello Giulietti
raffaello.giulietti at gmail.com
Fri Sep 28 07:50:41 PDT 2012
Hello,
are java.lang classes better served by the JVM than other classes?
Here's a small experiment.
I created a MyInteger class that exposes the very same implementation
of Integer.numberOfTrailingZeros(int), copied verbatim.
And here is a test that, on my JVM, shows that the implementation in
Integer is about 5 times faster. I tried several JVM flags, e.g.,
-server, -XX:+AggressiveOpts, -Xshare:off, unsatisfactorily. Similar
results with factor of about 3-5 are observed on other platforms.
Why the big performance difference? I know, micro-benchmarks are evil,
etc, etc, ... But this is hard to understand, except if Integer were
already super-optimized "a priori", intrinsically, while building the
JVM. Is this the case?
Greetings
Raffaello
---------------
public class Trailing {
private static int COUNT = 1 << 30;
public static void main(String[] args) {
warmup();
my();
their();
}
private static void warmup() {
int t = 0;
for (int i = 0; i < COUNT; ++i) {
t += MyInteger.numberOfTrailingZeros(i);
}
System.out.println("warmup, t=" + t);
}
private static void their() {
int t = 0;
long begin = System.nanoTime();
for (int i = 0; i < COUNT; ++i) {
t += Integer.numberOfTrailingZeros(i);
}
System.out.println((System.nanoTime() - begin) / 1000000 +
"ms, t=" + t);
}
private static void my() {
int t = 0;
long begin = System.nanoTime();
for (int i = 0; i < COUNT; ++i) {
t += MyInteger.numberOfTrailingZeros(i);
}
System.out.println((System.nanoTime() - begin) / 1000000 +
"ms, t=" + t);
}
}
------------------
public class MyInteger {
public static int numberOfTrailingZeros(int i) {
// HD, Figure 5-14
int y;
if (i == 0) return 32;
int n = 31;
y = i <<16; if (y != 0) { n = n -16; i = y; }
y = i << 8; if (y != 0) { n = n - 8; i = y; }
y = i << 4; if (y != 0) { n = n - 4; i = y; }
y = i << 2; if (y != 0) { n = n - 2; i = y; }
return n - ((i << 1) >>> 31);
}
}
More information about the mlvm-dev
mailing list