csharpc

System.Text.StringBuilder

A library or CoreLib type served from the framework’s IL: its row of the per-library table of ADR 0023 (columns explained there, under “Measurements”).

Library (switch) Correctness (samples from IL) Binary size, IL / shadow Compile cpu, IL / shadow Speed, IL / shadow (time) Lines removed on a flip Decision NativeAOT on the same host, csharpc / NativeAOT (tools/il-first/measure-aot.sh: stripped size; compile cpu; run, median of 7; instructions)
System.Text.StringBuilder and its chunk enumerator (CoreLib type, #304) all 69 samples that mention StringBuilder, plus the record, interpolation, format, tuple and regex samples (244 at -O0 and -O2) pass; sample 1309 (recorded from real .NET) for the generic shapes the framework’s handler uses on boxed values; found along the way: #305 (interface tests on boxed Nullable, enums and Half in generic code) neutral overall, smaller where StringBuilder is used by the corelib: linux-x86_64 regexoptions -11.5 KB (-0.5 %), regex -3.5 KB, collections -3.8 KB, async/linq/numbers +0.3 KB; hello, exceptions, typeinfo unchanged. A program that appends numbers and interpolations to a StringBuilder grows: the benchmark program 140 000 to 209 280 B (+49 %, the real handler’s generic formatting) linq 6.84 to 7.11 s CPU (+4 %) instructions per operation, 100 000 to 300 000 operations: Append(char) equal, Insert equal, ToString +8 %, Append(string) +99 % (27 to 53 per call: Buffer.Memmove is a call to libc for short strings, the shadow copied inline), Append(int) +46 %, AppendLine +88 %, Append($"...") +75 % (10.6 M to 18.8 M; was 10x slower until three IL folds: box T; isinst I and castclass I on a known T are constants, box T; callvirt I.M is T’s own method, typeof(T).IsEnum/IsValueType prune branches) 1 498 deleted and 44 added in corelib (StringBuilder.cs out; StringBuilderRuntime.cs and a Rune.AsSpan contract member in) Flipped. Security: bounds, capacity and ArgumentOutOfRangeException checks of Append/Insert/ToString are now upstream’s own code, not a port; Buffer.Memmove<T>’s element count is checked (no silent truncation). The speed and size costs of appending strings and numbers are the price; the compiler’s own interpolation lowering (the shadow’s fast path) cannot stand beside the real handler, closing the gap is a follow-up. stringbuilder_throughput: 215 000 / 1 345 360 B; compile cpu 7.1 / 12.6 s; run 3 968 / 1 525 ms (2.60x); 38.39 G / 12.34 G instructions