String += in a loop vs StringBuilder
Both build the same 2,000-character string. += copies about n²/2 characters; the builder copies about 2n. Double n and the first number quadruples while the second roughly doubles.
Most slow Java code is slow for a handful of ordinary reasons: the wrong algorithm or collection, needless allocation and boxing, string building in loops, exceptions and logging in hot paths, lock contention, and I/O done one byte or one query at a time. Measure first, fix the biggest cost, and measure again.
Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Rewrite a method that joins 1 to 10 with commas using += into one using StringJoiner, and print the result.
Given an array of 10 ints with duplicates, count distinct values using a HashSet instead of nested loops, and print the count.
Write a static final Pattern that matches product codes like ABC-1234, test it on three inputs, and print the results.
Explain it without notes
How do you approach a "the service is slow" report?
Why is s += x in a loop slow, and why is a + b + c not?
What are the costs of autoboxing, and how do you avoid them?
What is the N+1 query problem and how do you fix it?
Expected output
same text: true
length: 2000
chars copied (+=): 1001000
chars copied (sb): 4272