Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why avoid string.ToLower() when doing case-insensitive string comparisons?

I have read that when in your application you do a lot of string comparison and using ToLower method, this method is quite costly. I was wondering of anyone could explain to me how is it costly. Would appreciate any info or explanation. Thanks!

like image 440
Coding Duchess Avatar asked Feb 10 '15 20:02

Coding Duchess


People also ask

How do you compare strings case insensitive?

The most basic way to do case insensitive string comparison in JavaScript is using either the toLowerCase() or toUpperCase() method to make sure both strings are either all lowercase or all uppercase.

Is ToUpper better than ToLower?

ToUpper depends on what your strings contain more of, and that typically strings contain more lower case characters which makes ToLower more efficient.

Are string comparisons case-sensitive?

CompareTo and Compare(String, String) methods. They all perform a case-sensitive comparison.

Is JavaScript string comparison case-sensitive?

A general requirement while working in javascript is case-insensitive string comparisons.


2 Answers

See also writing culture-safe managed code for a very good reason why not to use ToLower().

In particular, see the section on the Turkish "I" - it's caused no end of problems in the past where I work...

Calling "I".ToLower() won't return "i" if the current culture is Turkish or Azerbaijani. Doing a direct comparison on that will cause problems.

like image 99
Wai Ha Lee Avatar answered Sep 19 '22 20:09

Wai Ha Lee


There is another advantage to using the String.Compare(String, String, StringComparison) method, besides those mentioned in the other answers:

You can pass null values and still get a relative comparison value. That makes it a whole lot easier to write your string comparisons.

String.Compare(null, "some StrinG", StringComparison.InvariantCultureIgnoreCase);

From the documentation:

One or both comparands can be null. By definition, any string, including the empty string (""), compares greater than a null reference; and two null references compare equal to each other.

like image 35
oɔɯǝɹ Avatar answered Sep 17 '22 20:09

oɔɯǝɹ