Why avoid string.ToLower() when doing case

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!


It's costly because a new string is "manufactured".

Compare that to calling, say, Equals with an overload that asks for a case-insensitive comparison. This allows the comparison to terminate, without having to create a new string, as soon as a mismatch is identified.


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.

链接地址: http://www.djcxy.com/p/2104.html

上一篇: MySQL全文搜索分数解释

下一篇: 为什么在做case时避免使用string.ToLower()