All publications

Magazine · 2011

Collateral Damage in the Altar of Expressiveness

Vassilios Karakoidas

A Greek magazine column on the gap between what Java's convenient constructs look like and what they cost — written against the belief that the language or the VM will quietly make your program fast.

Published in
Linux Inside (Greek), 2011
Citations
Not indexed by Google Scholar.
Cite as
LX11-1

The argument

Java is everywhere, and in the author's experience a good deal of it is written by people who assume the virtual machine will magically make their program run faster. The column stays deliberately on the side of coding style rather than VM tuning, and takes the expressive constructs one at a time.

  • foreach is slower than a plain for. It is implemented through Iterable, so every iteration is a hasNext() and a next() call. The advice is still to use it — it is more readable — except where a specific piece of code needs optimising.
  • Autoboxing hides work rather than removing it. An Integer used inside a loop over an int[] is unboxed on every pass; nothing in the source says so and nothing in the compile complains.
  • The JVM does not recycle your objects for you. Integer.valueOf caches, but only between −128 and 127, which a four-line program comparing instances with == demonstrates. Caching is documented in the Javadoc where it exists; assume nothing beyond it.
  • A program that prints without a main. Move the statement into a static initialiser and leave main() empty; it runs, prints and exits normally.

The title asks whether these are collateral damage on the altar of expressiveness. The column's answer is that the constructs are worth having as long as you know what they cost.

Written from the paper itself — the PDF linked above, which this site hosts.