Strings can't change. So joining strings in a loop makes a brand new string every time. A StringBuilder is a piece of text that can change, so building long text is fast.
Append adds to the end, without making a new string. Here, we build one, dash, two, and so on. Insert puts text at a position. Reverse flips the whole thing. Run it. The counting line, then the same line, reversed. Level reversed is still level. And the builder holds twenty four characters.
Main.javajava
public class Main { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); for (int i = 1; i <= 5; i++) { sb.append(i); if (i < 5) sb.append(" - "); } System.out.println(sb); sb.insert(0, "Count: "); sb.reverse(); System.out.println(sb); System.out.println(new StringBuilder("level").reverse() + " " + sb.length()); }}
We build a long string twice. First with plus, then with a StringBuilder. Nano time measures how long each one takes. Run it. Both made twenty thousand letters. And the StringBuilder was faster.
Main.javajava
public class Main { public static void main(String[] args) { long t1 = System.nanoTime(); String s = ""; for (int i = 0; i < 20000; i++) s += "x"; long t2 = System.nanoTime(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 20000; i++) sb.append("x"); long t3 = System.nanoTime(); System.out.println("Both made " + s.length() + " and " + sb.length() + " letters"); System.out.println("StringBuilder was faster? " + ((t3 - t2) < (t2 - t1))); }}
Output
Both made 20000 and 20000 letters
StringBuilder was faster? true
Use plus for a few joins, it's clear and fine. Use a StringBuilder when you join inside a loop. Call to string at the end, when you need a String. And remember, String dot join, and Collectors dot joining, are great too.