The copy hidden in a loop
transcript
A store app exports one hundred thousand pieces of text. The loop adds each piece to one string. It is correct. It looks fine. Now watch what Java does.
A Java string cannot be changed. So each plus equals builds a new string. It copies every character so far. The copies grow with the string.
Take a hundred thousand pieces of two letters. The first addition copies two characters. The next copies four. By the end, one addition copies two hundred thousand. In all, that copies about ten billion characters. On one laptop, that took four tenths of a second. A StringBuilder took under a millisecond.
Collect the pieces first. Adding to a list is cheap. Then build the string once. Each character is copied only a few times. In Java, use a StringBuilder. In Python or JavaScript, use join.
Languages differ here. Java copies every time. So does C plus plus s equals s plus x. Python and JavaScript often hide the cost. But the language does not promise it.
Collect the pieces. Build the string once. Full breakdown in the lecture.