为什么在进行不区分大小写的字符串比较时避免使用 string.ToLower()?

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

我了解到,当您在应用程序中进行大量字符串比较并使用 ToLower 方法时,这种方法的成本非常高。我想知道任何人都可以向我解释它是如何昂贵的。将不胜感激任何信息或解释。谢谢!

成本很高,因为新字符串是 "manufactured"。

将其与调用 Equals 进行比较,重载要求进行不区分大小写的比较。这允许在识别出不匹配时立即终止比较,而不必创建新字符串。

每次调用 ToLower() 时,都会创建一个新的字符串副本(而不是就地更改大小写)。如果您有很多字符串或长字符串,这可能会很昂贵。

来自 String.ToLower 文档:

Returns a copy of this string converted to lowercase.

另请参阅 writing culture-safe managed code 了解不使用 ToLower() 的充分理由。

特别是,请参阅有关土耳其语的部分 "I" - 它在我过去工作的地方造成了无穷无尽的问题...

如果当前文化是土耳其语或阿塞拜疆语,则调用 "I".ToLower() 不会 return "i"。直接比较会导致问题。

除了其他答案中提到的那些之外,使用 String.Compare(String, String, StringComparison) 方法还有另一个优点:

您可以传递 null 值并仍然获得相对比较值。这使得编写字符串比较变得更加容易。

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

来自文档:

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.

正如有人已经回答的那样,ToLower() 将创建一个新的字符串对象,与使用 "IgonoreCase" 相比,这是额外的成本。如果这个 ToLower 被频繁触发,你最终会在你的堆中创建很多小对象,并且会增加垃圾收集时间,这会成为性能损失。