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!
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.
ToUpper depends on what your strings contain more of, and that typically strings contain more lower case characters which makes ToLower more efficient.
CompareTo and Compare(String, String) methods. They all perform a case-sensitive comparison.
A general requirement while working in javascript is case-insensitive string comparisons.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With