# "Why + in a loop is slow" and "Append to a list, join once": times both# ways for 20,000 and 40,000 lines. Timings depend on the machine.use io;
use strings;
use time;
funcviaPlus(n asint) {
def out asstringinit"";
for (def i in0..$n) {
$out = $out + "line\n"; # copies all of $out, every round
}
return$out;
}
funcviaJoin(n asint) {
def lines aslistofstringinit [];
for (def i in0..$n) {
$lines[] = "line"; # grows in place: amortised O(1)
}
def out asstringinitstrings.join($lines, "\n") + "\n";
return$out;
}
funcmillis() {
returntime.unixMillis(time.now());
}
io.printf("| Lines | + in a loop | append, then join |\n");
for (def n in [20000, 40000]) {
def t0 asintinitmillis();
def a asstringinitviaPlus($n);
def t1 asintinitmillis();
def b asstringinitviaJoin($n);
def t2 asintinitmillis();
if ($a != $b) { throw Error{kind: "value", message: "outputs differ"}; }
io.printf("| %d | %d ms | %d ms |\n", $n, $t1 - $t0, $t2 - $t1);
}