StringBuilder in Java
Strings are immutable, so repeated concatenation copies; a builder does not.
// strings are immutable; a builder makes many appends cheap
var sb = new StringBuilder();
for (int i = 1; i <= 5; i++) {
sb.append("step ").append(i).append('\n');
}
sb.insert(0, "the plan:\n");
System.out.println(sb);
System.out.println("length " + sb.length());
How it works
appendchains and grows the buffer in place.insert(0, ...)writes at any position, even the front.- Printing the builder pays the string cost once, at the end.
Keywords and builtins used here
forintnewvar
The run, in numbers
- Lines
- 8
- Characters to type
- 264
- Tokens
- 85
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 54 seconds.
Step 4 of 4 in Strings, step 7 of 29 in Language basics.