Brian Goetz is one of my favorite Java experts(he’s also a pretty solid poker player too with a streak of gambool). He does an excellent job of keeping people updated on real world Java performance issues. In the article above he describes some real world situations where Java will outrun C++. In particular note Brian’s comment that these days object pooling in Java is almost always a bad idea.
I knew that Java can run faster than C++, and I’d been searching for example code which would show it. Ironically, the example was in an area where people(including myself) thought C++ would really do better than Java: memory allocation. It just goes to show that in the fast changing world of software, today’s gospel may be tomorrow’s urban legend.
I wrote up a quick test to confirm that Java did indeed outrun C++, the results are below. The summary is: on my desktop Linux 2.4 machine doing a billion new/free operations on a tiny class takes almost 2 mins in C++ but with Java using JDK 1.5 it took less than 30 seconds. I’m curious how it performs on other systems as well.
hubt{4:41pm}hubert[~/test]:; uname -aLinux hubert 2.4.21-32.0.1.EL #1 Wed May 25 14:36:20 EDT 2005 i686 i686 i386 GNU/Linuxhubt{4:41pm}hubert[~/test]:; cat a.cc#include <stdlib.h>class A { int j;};
int main(int argc,char **argv) { system("date"); for(int i = 0; i < 1000*1000*1000; i++) { A *a = new A(); delete a; } system("date");}hubt{4:41pm}hubert[~/test]:; g++ a.cchubt{4:41pm}hubert[~/test]:; g++ --versiong++ (GCC) 3.2.3 20030502 (Red Hat Linux 3.2.3-52)Copyright (C) 2002 Free Software Foundation, Inc.This is free software; see the source for copying conditions. There is NOwarranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
hubt{4:41pm}hubert[~/test]:; ./a.outSun Oct 9 16:41:29 PDT 2005Sun Oct 9 16:43:10 PDT 2005hubt{4:43pm}hubert[~/test]:; cat A.javapublic class A { int i; public static void main(String []args) { System.out.println(new java.util.Date()); for(int i = 0; i < 1000*1000*1000; i++) { A a = new A(); } System.out.println(new java.util.Date()); }}
hubt{4:43pm}hubert[~/test]:; javac A.javahubt{4:43pm}hubert[~/test]:; java -versionjava version "1.5.0_01"Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_01-b08)Java HotSpot(TM) Client VM (build 1.5.0_01-b08, mixed mode, sharing)hubt{4:43pm}hubert[~/test]:; java ASun Oct 09 16:43:40 PDT 2005Sun Oct 09 16:44:06 PDT 2005