Why a loop of plus is slow.
transcript
A hundred thousand order codes. One text report. Newest first. Put each code in front. It is correct. It is slow. The loop looks harmless. Its cost is hidden.
A string cannot change. So each step makes a new string. It copies the whole text so far. Then it adds one code. The text only gets longer. Like taping strips together. Each strip is copied first. The strip gets longer each time.
A hundred thousand codes. Fifty five billion characters copied. A builder writes one point one million. That is fifty thousand times fewer. The loop copies the same text again. Doubling the codes makes four times the work.
In Java, eighty thousand codes took one point three seconds. A builder took under one millisecond. Python and C plus plus show the same. Twice the codes took four times longer. Collect first. Build once. The builder holds the whole text.
Count the copies. Full breakdown in the lecture.