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.
3 points to say:
s += xin a loop copies the whole string every turn.- For many appends use
StringBuilder. a + b + con 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.