String Format 3x Faster in Java 17

java November 1, 2021

From our friends at JavaSpecialists.eu, we have “String.format() 3x faster in Java 17”, a post that shows how, for simple cases, String.format() is much faster than it used to be.

This is a really interesting statement, too. Here’s why Heinz Kabutz (the author) suggested using String.format(), even though in older JVMs it was far slower than some other mechanisms:

Concatenate using String.format()

  • Simpler to read and maintain
  • For performance critical, use + for now
  • In loops still use StringBuilder.append()

In a way it was a hard sell. Why would a programmer knowingly do something that was 40x slower?

The caveat was that the engineers at Oracle knew that String.format() was slow and were working on improving it. We even found a version of Project Amber that compiled the format() code to be the same speed as the plain + operator.

There are caveats, of course: the more complex the formatting expression is, the slower String.format() becomes. But for the common cases, it’s far, far faster than it used to be, and unless you’re looking at very performance-critical code, the gains in simplicity and maintenance are probably worth it.

in java

Reading time: 1 minute.