Mike's face
Saturday, October 20th, 2018








Java sometimes faster than C

Monday December 20, 2004 14:37

Still think that Java is interpreted and/or slow?  Let's set the performance record straight, shall we?

Take the following cpp code:

include <iostream>

using namespace std;

double factorial(int n)
{
    return n > 1 ? n * factorial(n - 1) : n;
}

double factorials(int n, int count)
{
    double total = 0;
    for (int i = 0; i < count; i++)
        total += factorial(n);
    return total;
}

int main()
{
    double total = factorials(100, 1000000);
    cout << total << endl;
    return 0;
}

and the following Java code:

public class Test
{
    private static double factorial(int n)
    {
        return n > 1 ? n * factorial(n - 1) : n;
    }

    private static double factorials(int n, int count)
    {
        double total = 0;
        for (int i = 0; i < count; i++)
            total += factorial(n);
        return total;
    }

    public static void main(String[] args) throws Exception
    {
        for (int i = 0; i < 6; i++)
        {
            long time = System.currentTimeMillis();
            double total = factorials(100, 1000000);
            System.out.println((System.currentTimeMillis() - time) + " " + total);
        }
        System.exit(0);
    }
}

Compile:

cc -O3 -o test -lstdc++ test.cpp
javac Test.java

Run:

$ time ./test
9.33262e+163

real    0m2.509s
user    0m2.428s
sys     0m0.014s

$ java Test
1867 9.332621544205042E163
1678 9.332621544205042E163
1676 9.332621544205042E163
1651 9.332621544205042E163
1665 9.332621544205042E163
1676 9.332621544205042E163

$ java -server Test
746 9.332621544205042E163
773 9.332621544205042E163
730 9.332621544205042E163
729 9.332621544205042E163
768 9.332621544205042E163
728 9.332621544205042E163

Possible conclusions:

  • Java can be twice as fast as optimized C++
  • The GNU C++ compiler is inefficient
  • Java compiles to machine code
  • Java in "server" mode compiles to machine code earlier than in normal "client" mode

Definite myth:

  • C++ is always faster than Java

(C) Copyright 2004-2007 Mike Pot