ToString() v nameof() performance comparison when getting a string value from a enum option

The benchmarks (originally published on LinkedIn) below from ¬†show’s that there’s a big performance difference between using ToString() and nameof() when we are trying to get the string representation of a particular enum value…

Why?

… Well we can see from the IL below that nameof is evaluated at compile time and basically hardcodes the value into the generated IL, while ToString() is evaluated at runtime and has the overhead of a function call.

This means we need to be careful not to change the enum without recompiling any projects which reference it via nameof(), otherwise we’ll get old strings representing the enum when the referencing project was compiled, not when the enum project was recompiled after the change.

Note… in theory these two methods are intended for different things… in theory.. BUT… in practice I’ve seen countless instances where devs just want the as is string of the enum value (in this case ‘Published’) and both nameof and ToString give them this so if we are in a hot loop and once we know about the above gotcha switching to nameof() can be a good optimisation.

Leave a Reply

Your email address will not be published.