Skip to content
Advertisement

String vs StringBuffer. Tip of IDEA

Intellij Idea offers to replace the following:

JavaScript

To:

JavaScript

As far as I know it’s less effective (mutable/immutable). So, what’s better?

Advertisement

Answer

The second one compiles to the same byte-code as the first one, except it uses a non-synchronized StringBuilder instead of a synchronized StringBuffer. So it’s not only much more readable, but also slightly faster. I’d choose the second one.

Using a StringBuilder is useful when concatenating in a loop, to avoid creating many temporary String objects:

JavaScript

should be replaced by

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement