I had a hot loop stamping out order keys — little strings like ORD-0000042-US — a couple million of them per refresh. The code was the most boring thing in the file, so of course that's where the allocation profiler kept parking. I figured I'd reach for string.Create , the usual "stop allocating intermediate strings" move, get my speedup, and go home. I got half of what I expected. The interesting half.
Here's the code I started with. It's what most of us write without thinking, and honestly it's fine:
static string ConcatKey ( int id , string region ) => "ORD-" + id . ToString ( "D7" ) + "-" + region ;
Enter fullscreen mode
Exit fullscreen mode
Clean, readable, obviously correct. But look at what it allocates. There's the final string, sure, you can't avoid that one. And then there's id.ToString("D7") — a whole separate seven-character string that exists for one reason: to be copied into the concatenation and then immediately thrown away. Every single call makes one.…