вторник, 24 июня 2008 г.

When Java can be faster than C++

In practice, Java always slower than C/C++. But, i found one occurrence when Java really more fast. Let's see.

At first, i write little C++ code, test.cc like this:

#define ALLOCATIONS 200000000

int main(void) {
int i;

for( i = 0; i < ALLOCATIONS; ++i )
delete (new int(i));

}

then, compile and run:

cy6ergn0m@d-espb04-127-128 ~/test $ g++ -O3 test.cc
cy6ergn0m@d-espb04-127-128 ~/test $ time ./a.out
./a.out 22,86s user 0,01s system 100% cpu 22,867 total
cy6ergn0m@d-espb04-127-128 ~/test $

Note time: 22.86s

Then, i wrote in Java like this:

public class Main3 {

private static final int SZ = 200000000;

public static void main ( String[] args ) {

for( int i = 0; i < SZ; ++i )
new Integer(i);
System.gc();
}
}

At last, i use System.gc() to call GC because, someone can say, that this code does not deletes anything..

Ok, lets run it:

cy6ergn0m@d-espb04-127-128 ~/NetBeansProjects/JavaApplication12 $ time java -jar dist/JavaApplication12.jar
java -jar dist/JavaApplication12.jar 2,34s user 0,13s system 99% cpu 2,489 total

Note time here: 2.34s


Summary
This test shows us, that Java has more fast allocator/deallocator. C++ take too many time for object allocation. Here you can see that it's about 10 times slower (22.86s vs 2.34s).

But, if I'll try to do with allocated objects something - C++ will faster.

Currently, it only first incident when Java faster than C that I saw. If somebody know any other, please, send me link.