There are a number of ways to compare strings. Are there performance gains by doing one way over another?
I\'ve always opted to compare strings like so:
If the equality operator actually performed worse than CompareTo
- wouldn't Microsoft make the implementation of the equality operator call CompareTo
?
Just use the equality operator to test for equality.
There was a pretty similar question recently regarding the fastest way to trim a string, but it was basically benchmarking the different ways of comparing them.
You can check out the benchmarks on this post.
Here is the most complete and helpful MSDN guide for string comparison I have found.
Use comparisons with StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase for better performance.
Read Jeff’s The Best Code is No Code at All. foo.CompareTo(bar) == 0
: horrible visual clutter. Takes up a lot of space and conveys no interesting meaning. In fact, it emphasizes a lot of irrelevant stuff which deflects attention away from the real problem.
If there’s no well-defined reason for using this longer variant, don’t.
As for performance: it simply doesn’t matter for this simple case. If the equality operator ==
should really perform worse than CompareTo
, feel free to file a bug report with Microsoft. This must not happen.