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!
- Unless these are "significantly large" strings or they are of "innumerable quantity", this likely won't be a bottleneck .. ever. That being said, such normalization process - and especially in the case of in-memory strings - is a round-about way to describe the desired task. But such normalization is not always "bad", especially if the results are used [otherwise] anyway.user2864740– user28647402015-02-10 20:14:05 +00:00Commented Feb 10, 2015 at 20:14
5 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.
Comments
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.
4 Comments
string.StartsWith() will throw for a null argument. See msdn.microsoft.com/en-us/library/baketfxw%28v=vs.110%29.aspxStartsWith() first before calling Compare()? string Compare() is a 'smart' method, it will stop comparing after the first mismatch. -- I wouldn't be so concerned about performance, unless you have an actual performance problem. And when you do, use a profiler to find the actual bottleneck. I think you will find it is not were you will think it is.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.
Comments
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.