In a Java framework I’m working on, ‘pairs’ arise everywhere. Unfortunately in contrast to e.g. C++, Java doesn’t include a predefined ‘pair’ class. C++ templates are really nice because of the way they are complied and optimized (in particular they also handle what Java calls ‘native datatypes’); Java generics aren’t up to par with that. (But yes, Java offers other benefits, such as being much easier to parse and thus refactor). Anyway, this is not going to be a rant on Generics.

So I have this interface in Java called Pair<FIRST,SECOND> along with two implementations SimplePair<FIRST,SECOND> and ComparablePair<FIRST extends Comparable<FIRST>,SECOND extends Comparable<SECOND>>.

For performance reasons, SimplePair is declared ‘final’, and so is ComparablePair. It’s written everywhere that making classes final can make a large difference in Java, and since these objects will be used in a lot of places, it seems reasonable to care about this here.

However, it would often be nice to have better readable code, that is assuming I’m using SimplePair<Monkey,Banana>, it would then be nice to make a derived class BananaPreference extends SimplePair<Monkey,Banana>, with added methods getMonkey() and getPreferredbanana() to make the resulting code more readable.

Having readable code is also often quite as important as having performant code, after all …

If someone with solid experience in Java optimization has some ideas to share, please do so! Email: erich AT debian DOT org - no comments in blog.

Right now, I have one idea on how it could be possible to achieve both (seriously, I could use some feedback from Java Gurus on that): make SimplePair and ComparablePair abstract, all methods there final, then derive final classes as needed. Does that combine the benefits?

[Update: I received from Joachim Sauer the following helpful link: JavaOne presentation on performance tuning and various VMs. Basically this seems to indicate that in all these common situations, any modern Java VM should be able to figure out the inlining options automatically and optimize appropriately, so it won’t benefit from any “final” hint by the developer. Note that a C++ compile doesn’t do runtime optimization, but allows compile time optimization at a much lower level, so this rule doesn’t apply to C++.]