I just observed a weird performance issue in some Java toy example. Here is the complete program:
import java.util.Random;
public class Weird
{
public static long fib(int n)
{
long a = 0;
long b = 1;
for (long i = 0; i < n; ++i) // note: loop counter of type long
{
long c = a + b;
a = b;
b = c;
}
return a;
}
public static void main(String[] args)
{
System.out.print("Warming up the JIT... ");
warmUpTheJIT();
System.out.println("Starting measurement");
long bogus = 0L;
long before = System.nanoTime();
for (int i = 0; i < 500_000_000; ++i)
{
bogus += fib(46);
}
long after = System.nanoTime();
System.out.println(bogus);
long duration = after - before;
long ms = duration / 1_000_000;
System.out.println(ms +" ms");
}
private static void warmUpTheJIT()
{
Random rand = new Random();
long bogus = 0L;
for (int i = 0; i < 1_000_000; ++i)
{
bogus += fib(rand.nextInt(47));
}
System.out.println(bogus);
}
}
The code takes 21 seconds on my system (64 Bit Java 8 VM). However, if I change the loop counter from long
to int
, it only takes 27 MILLIseconds. That's about three orders of magnitude faster.
So... why does the type of a loop counter make such a huge difference?