Menu

The string.Create I Didn't Need
📰

The string.Create I Didn't Need

DEV Community: dotnet·Sukhpinder Singh·4 days ago
#Ih22RNps
#devtodotnet#devto#dev#string#bytes
Reading 0:00
15s threshold

A profiler started this one. I had a cache lookup on a hot path, and the key got built with string interpolation. During review someone suggested string.Create would allocate less. Reasonable. That's the standard advice when you're hunting garbage. So I went to make the swap, and out of habit I measured both before committing. They allocated exactly the same. Byte for byte. The thing I was "fixing" was already as lean as the fix.

The real lesson turned out to be somewhere I wasn't even looking.

The key, three ways

The key looks like user:42:profile:eu-west . An int in the middle, strings on either side. Here are the three ways I had on the table.

string NaiveConcat ( int id , string region ) => "user:" + id + ":profile:" + region ;

string Interpolated ( int id , string region ) => $"user: { id } :profile: { region } " ;

string Created ( int id , string region ) { int digits = id == 0 ? 1 : ( int ) Math . Floor ( Math . Log10 ( Math .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.