✅ Am I using NumberFormatInfo properly?
I have a list of ca. 400 numbers which I want to convert to percentage strings as part of an endpoint. I know I will only ever want two decimal places or three decimal places. I was wondering about the impact of allocating a new
The results indicate caching is better but the end result after all the numbers in terms of allocs or nanoseconds saved seems unlikely to be significant (probably 217kB memory saved, or 12 microseconds faster). Is this premature optimization? OR is there a more idiomatic way to use NumberFormatInfo that I'm missing here?
NumberFormatInfo
each time so I whipped up some code:
The results indicate caching is better but the end result after all the numbers in terms of allocs or nanoseconds saved seems unlikely to be significant (probably 217kB memory saved, or 12 microseconds faster). Is this premature optimization? OR is there a more idiomatic way to use NumberFormatInfo that I'm missing here?
4 Replies
depends on scale tbh. It's not really bad to prematurely optimize here if you know you'll ever only need one or two formats, but beyond that I'd have to see more discrepancy in benchmarks at the scale you're expecting to care
part of the reason for needing individual objects is outlined a bit here: https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-globalization-numberformatinfo#dynamic-data
System.Globalization.NumberFormatInfo class - .NET
Learn more about the System.Globalization.NumberFormatInfo class.
right, yeah I am fairly sure it would only ever be 2 or 3, and it's data I'm generating in my web backend and sending to be rendered into a UI
Given that, there's an argument to make it culture specific, but I think retrieving the user's current culture is not really worth the hassle at this stage
Scale is pretty small, this endpoint will probably only be hit a couple times an hour if that 😛
It definitely is not really worth it for this specific use case but I do like to learn more about .NET when these things come up