Sitemap
Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Member-only story

ToString vs nameof Performance

1 min readApr 14, 2023

--

This is a short post — barely an article. You can read it over your morning coffee or tea and then scroll onward.

I was going through a codebase the other day and I noticed a lot of methods doing effectively the same thing in two different ways:

public static bool PerformSomeCheck_Version_1(string someStringToCheck)
{
return someStringToCheck == Fruits.Pear.ToString();
}

...

public static bool PerformSomeCheck_Version_2(string someStringToCheck)
{
return someStringToCheck == nameof(Fruits.Pear);
}

...

enum Fruits
{
Apple,
Banana,
Orange,
Pear
}

Both Fruits.Pear.ToString() and nameof(Fruits.Pear) return the string "Pear", so I wondered which one was faster. nameof returns a compile-time constant, and has no effect at run-time, whereas ToString is an ordinary C# method that gets called at run-time. With this in mind, I had a pretty good guess as to which was going to be faster, but to confirm things, I ran both varieties through BenchmarkDotNet and saw that nameof is in fact 30 times faster than ToString in this case.

Of course, we’re talking about nanoseconds here, so this is firmly in micro-optimization territory, and I wouldn’t recommend anyone refactor existing code for the sake of this change, unless you’re working at the level where nanoseconds are important to you, and if that’s the case you’re probably writing C or Rust code anyway. I just thought it was interesting to mention.

Thank you for reading!

--

--

Nerd For Tech
Nerd For Tech

Published in Nerd For Tech

NFT is an Educational Media House. Our mission is to bring the invaluable knowledge and experiences of experts from all over the world to the novice. To know more about us, visit https://www.nerdfortech.org/.

Michael Moreno
Michael Moreno

No responses yet