LYR-SEM0220
a string grown with '+' in a loop
In a loop, a string kept across its rounds is assigned itself with something added: s = s + x or s += x.
Explanation
A string never changes, so each + makes a new one and copies all that came before: n rounds copy on the order of n² bytes.
Append to a StringBuilder in the loop and take its toString() after it.
Wrong
fn main(): void {
var line = "";
for (i in 0..3) {
line = line + f"{i}";
}
let _ = line;
}
Right
import std.string { StringBuilder };
fn main(): void {
let line = StringBuilder.new();
for (i in 0..3) {
line.append(i);
}
let _ = line.toString();
}