Now blogging at diego's weblog. See you over there!

a simple performance test of java generics

Now that Generics are coming to the Java Platform (in the next JDK), I was curious as to how they would perform, since everything depends in how efficiently they are managing the type management internally (yes, in theory there shouldn't be much difference, but you never know). So I downloaded the Early Access prototype to add generics to JDK 1.4.x, and did a couple of simple tests, with the idea of finding out two things: 1) whether there would be a noticeable performance hit and 2) whether it was necessary to modify JDK 1.4 to run generics-enabled classes.

So, I created two simple classes: and (Here is a ZIP file with both Java sources and the compiled classes).

Basically the classes do the same thing: they create first a LinkedList and add one million Integer objects to it, and then iterate through each, and then create a Vector and do basically the same. The program measures the time in milliseconds it takes to go from one step to the next, and prints it out. The only difference between the classes is that one uses generics (so that you avoid having to cast the object to an Integer when obtaining it) and the other uses standard Java.

First, using generics was as easy as switching javac to the shell file they provide in the kit (with a couple of modifications), and then compiling (there is also a way of using generics by simply using the standard javac with an additional JAR provided in the kit). What's really cool is that once the classes are compiled, it isn't necessary to have the new JAR in the classpath, classes that use generics compile to standard bytecode that can run under JDK 1.4 with no modifications.

Regarding the performance, these are the results:

Without Generics:

Linked List:

Time to add=4747 (msec)
Time to iterate=290 (msec)
Time to add=5068 (msec)
Time to iterate=190 (msec)
With Generics:

Linked List:

Time to add=4787 (msec)
Time to iterate=301 (msec)
Time to add=5067 (msec)
Time to iterate=180 (msec)
(These were run under the same machine load, on a P3-800 with 384 MB or RAM, with JDK 1.4.1_01 -- The Vector tests are slower because the methods in Vector are synchronized).

So there is basically no performance hit! This is excellent, specially considering this is an early access release. We get the advantages of static typing on data structures with no performance disadvantages, at least for these simple tests. I am tempted to begin using it right now for spaces... as Homer would say "mmmm.... generics..." :-)

Later: the file sizes of the two classes are different, but there's a surprise in store: the class that uses generics is smaller. TestGenerics.class is 1,403 bytes, and TestNoGenerics.class is 1500 bytes. Cool!

Categories: technology
Posted by diego on January 16 2003 at 7:58 PM

Copyright © Diego Doval 2002-2011.
Powered by
Movable Type 4.37