Alex Rivera | Logout

String comparison performance in C#

Asked 2009-05-13T16:33:54.250
25

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:

string name = "Bob Wazowski";
if (name.CompareTo("Jill Yearsley") == 0) {
    // whatever...
}

But I find few people doing this, and if anything, I see more people just doing a straight == comparison, which to my knowledge is the worst way to compare strings. Am I wrong?

Also, does it make a difference in how one compares strings within LINQ queries? For example, I like to do the following:

var results = from names in ctx.Names
              where names.FirstName.CompareTo("Bob Wazowski") == 0
              select names;

But again, I see few people doing string comparisons like so in their LINQ queries.

Edit
Report

2 Answers

10

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.

answered 2009-05-13T16:50:10.683
5

Well MSDN states you shoul use the comparision function according to the task you need to perform:

The CompareTo method was designed primarily for use in sorting or alphabetizing operations. It should not be used when the primary purpose of the method call is to determine whether two strings are equivalent. To determine whether two strings are equivalent, call the Equals method.

So if its not about sorting and the retrun value is not important i would say one should use the:

first.Equals(second) or if the comparison is culture specific for example in languages like in german:

String.Equals(first, second, StringComparison.CurrentCulture)

Take a look a these links:

How to: Compare Strings (C# Programming Guide)

String.CompareTo Method (Object)

answered 2013-01-14T06:55:01.867

Your Answer