Performance Tip: Don't use StringBuilder for compile time constants.

Overview

Using String + String notation is simpler than using a StringBuilder. It can be slower but for compiler time constants is faster to use.

When using String + String is faster

One of the few optimisations the compiler will do is inline compile time constants.
String + expressions which can be evaluated at compile time and don't need to be computed at runtime.

From ContextFinder.find()
final String jaxbContextFQCN = JAXBContext.class.getName();
final StringBuilder resource = new StringBuilder().append("META-INF/services/").append(jaxbContextFQCN);
However, the compiler can compute the resource variable to a String literal at compile time improving performance.
final String jaxbContextFQCN = JAXBContext.class.getName();
// becomes a String literal.
final StringBuilder resource = "META-INF/services/" + jaxbContextFQCN;
Not only is this simpler, but also faster.

Comments

  1. I didn't understand the compiler optimization you try to explain in the above post. In a sample when I try

    String className = StringVsStringBuilderApp.class.getName();
    String s = className + " Some Compile Time Constant";

    I can still see the class file having the same two statements. So it looks like the string variable s is not evaluated by the compiler. Can you detail a bit on the optimization?

    ReplyDelete

Post a Comment

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

System wide unique nanosecond timestamps

What does Chronicle Software do?