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

后端 未结 5 1129
温柔的废话
温柔的废话 2021-01-19 05:38

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

相关标签:
5条回答
  • 2021-01-19 05:45

    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.

    0 讨论(0)
  • 2021-01-19 05:47

    Each time you call ToLower(), a new copy of the string will be created (as opposed to making the case changes in-place). This can be costly if you have many strings or long strings.

    From String.ToLower docs:

    Returns a copy of this string converted to lowercase.

    0 讨论(0)
  • 2021-01-19 05:56

    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.

    0 讨论(0)
  • 2021-01-19 05:57

    As somebody already answered, ToLower() will create a new string object, which is extra cost comparing to using "IgonoreCase". If this ToLower is triggered frequently, you end up creating a lot of small objects in your heap, and will add Garbage Collection time, which becomes a performance penalty.

    0 讨论(0)
  • 2021-01-19 06:01

    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.

    0 讨论(0)
提交回复
热议问题