SteelReed

Search

Search posts, questions…

Java CoreQuestion 15 / 43

Middle

What is the difference between String, StringBuilder and StringBuffer? Why is + concatenation in a loop slow?

Short answer

String cannot change; StringBuilder can change and is the fastest; StringBuffer is like Builder but with locks, rarely used now.

n passesarray full, double its += item at pass knew Stringcopy k old partsO(n²) + lots of garbagesb.append(item)amortized O(1)

3 points to say:

  1. s += x in a loop copies the whole string every turn.
  2. For many appends use StringBuilder.
  3. a + b + c on one line is already optimised.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.