Comparing speed of ToUpper, ToUpperInvariant, ToLower and ToLowerInvariant in .NET Framework and .NET Core
While I was reviewing some code week or two back, I got idea to test what’s the speed difference between
ToLowerInvariant. Of course, these methods are not doing the same thing, but sometimes it doesn’t really matter and if any is sufficient then, maybe, performance wins. Or at least I thought it’s going to be interesting to see whether there’s a difference and how much.
Obviously, the problem is that the outcome is very likely dependent on the string being processed and unless I want to test all possible combinations I have to choose some subset. My first, self-imposed, constraint was to consider only strings containing
9, basically only letters and numbers from ASCII. Once you start mixing in national characters it’s really a different game and this comparison starts to fall apart. From these characters I made strings of length between 1 to 10 and then 100 and 255. I made bunch of permutations from these and used the trusty BenchmarkDotNet to execute it multiple times to get even more data averaging all the results at the end (one run took almost 3 hours). Thus for i.e. strings of length 1 I ended up testing these:
The CPU was Intel Xeon E5-2673 v3 2.40GHz. The .NET Framework used was
.NET Framework 4.7.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3163.0 and .NET Core was
.NET Core 2.1.4 (CoreCLR 4.6.26814.03, CoreFX 4.6.26814.02), 64bit RyuJIT. All times are in
Let’s first talk about regular .NET Framework.
ToLower is slowest. The other three are mostly the same. But in general,
ToLowerInvariant is fastest, then
ToUpper and then
Surprisingly, the .NET Core is roughly 2,6× faster across the results.
I was not expecting that. The
ToLower is still slowest and then the remaining methods. Compared to .NET Framework the pattern on remaining three is not consistent. But if you’d ask me, I would order it
ToUpper fastest, then
ToUpperInvariant and then
The memory allocations seem to be same for both .NET Framework and .NET Core for all methods for given string lengths.
Given the speed of the method also depends on the string itself I don’t think we can come to a one-size-fits-all conclusion. But as long as you have a choice, in general, avoiding
ToLower seems to be a safe bet. Especially given that string comparisons in upper case are preferred (but one should not forget about case insensitive string handling in the first place).
Now I have the temptation to explore where does the speed difference come from (but I have a feeling I would burn a lot of time exploring that). Or, if you know, teach me in the comments.