Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient(?) string comparison

What could possibly be the reasons to use -

bool result = String.Compare(fieldStr, "PIN", true).Equals(0);  

instead of,

bool result = String.Equals(fieldStr, "PIN", StringComparison.CurrentCultureIgnoreCase);

or, even simpler -

bool result = fieldStr.Equals("PIN", StringComparison.CurrentCultureIgnoreCase);

for comparing two strings in .NET with C#?

I've been assigned on a project with a large code-base that has abandon use of the first one for simple equality comparison. I couldn't (not yet) find any reason why those senior guys used that approach, and not something simpler like the second or the third one. Is there any performance issue with Equals (static or instance) method? Or is there any specific benefit with using String.Compare method that even outweighs the processing of an extra operation of the entailing .Equals(0)?

like image 916
atiyar Avatar asked Jun 26 '13 05:06

atiyar


1 Answers

I can't give immediate examples, but I suspect there are cases where the first would return true, but the second return false. Two values maybe equal in terms of sort order, while still being distinct even under case-ignoring rules. For example, one culture may decide not to treat accents as important while sorting, but still view two strings differing only in accented characters as unequal. (Or it's possible that the reverse may be true - that two strings may be considered equal, but one comes logically before the other.)

If you're basically interested in the sort order rather than equality, then using Compare makes sense. It also potentially makes sense if the code is going to be translated - e.g. for LINQ - and that overload of Compare is supported but that overload of Equals isn't.

I'll try to come up with an example where they differ. I would certainly say it's rare. EDIT: No luck so far, having tried accents, Eszet, Turkish "I" handling, and different kinds of spaces. That's a long way from saying it cant happen though.

like image 102
Jon Skeet Avatar answered Oct 13 '22 08:10

Jon Skeet