Francesco Galgani
Francesco Galgani

Reputation: 6249

Codename One StringBuilder vs "+" operator between Strings

I noted that the Javadocs of Oracle StringBuilder and of Codename One StringBuilder have differences. For example, the first is not thread safe and the second is thread safe.

However, my question is about the Codename One version of the StringBuilder, in particular about this incomplete sentence, in which the examples are missing: «String builders are used by the compiler to implement the binary string concatenation operator +. For example, the code: is compiled to the equivalent of:».

So, my question is if there isn't any advantage in the use of StringBuilder instead of the + operator between Strings. I noted that in the Codename One sources you use a lot the StringBuilder, but in my apps if I concatenate one hundred of String or if I append them using a StringBuilder is exactly the same thing in terms of performance and memory? Even if the content of these Strings is not known at compile time?

Upvotes: 1

Views: 47

Answers (2)

maaartinus
maaartinus

Reputation: 46422

Java 8 compiles a = b + c using StringBuilder into the bytecode as there's no "string addition" in the JVM. The JIT has special optimization for many resulting patterns (irrelevant here).

As CN1 starts with bytecode (and can't see the sources), the results must be the same. The bytecode always allocates a StringBuilder for an expression and uses the produced string. When appending in loops, you can do much better by skipping the string and working with the same builder all the time.

My rule is: Always use StringBuilder when appending in loops, never bother otherwise.

Upvotes: 1

Shai Almog
Shai Almog

Reputation: 52760

This is a mistake in the JavaDocs probably because they were derived from StringBuffer as a starting point. StringBuilder isn't threadsafe. I personally use the + / += operators which are both pretty efficient in current versions of javac (current being Java 8+).

The advantage of StringBuilder is if you have something the compiler can't detect. E.g. if you have a string to which things are appended in a relatively long scope or even one that exceeds method boundaries. In that case the compiler will have to create multiple StringBuilder and String instances instead of a single instance of StringBuilder. Since the compiler abstracts that you'd need to guess what it does and how smart it can be.

Upvotes: 1

Related Questions