什么是C#中的最快的(内置)比较字符串类型 [英] What is the fastest (built-in) comparison for string-types in C#

查看:164
本文介绍了什么是C#中的最快的(内置)比较字符串类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是内置最快的字符串类型在C#中的比较法?我不介意的印刷/语义含义:其目的是使用有序列表比较,以在大集合快速搜索。我认为,只有两种方法:比较 CompareOrdinal 。什么是最快的?

What is the fastest built-in comparison-method for string-types in C#? I don't mind about the typographical/semantical meaning: the aim is to use the comparator in sorted lists in order to search fast in large collections. I think there are only two methods: Compare and CompareOrdinal. What's the fastest?

此外,有没有对那些字符串比较更快的方法?

Additionally, is there is a faster method for those string-comparisons?

推荐答案

我假设你想有一个小于/等于/大于比较,而不是仅仅平等;平等是一个稍微不同的主题,虽然原理基本相同。如果你实际上只像一个搜索的存在排序列表,我会考虑使用词典<字符串,XXX> 而不是 - 你真的需要所有的排序

I'm assuming you want a less-than/equal/greater-than comparison rather than just equality; equality is a slightly different topic, although the principles are basically the same. If you're actually only searching for presence in something like a SortedList, I'd consider using a Dictionary<string, XXX> instead - do you really need all that sorting?

String.CompareOrdinal 或使用的String.Compare 其允许提供的比较,并指定一个序号(区分大小写)比较,如的String.Compare(X,Y,StringComparison.Ordinal)将是最快的。

String.CompareOrdinal, or using an overload of String.Compare which allows the comparison to be provided, and specifying an ordinal (case-sensitive) comparison, e.g. String.Compare(x, y, StringComparison.Ordinal) will be the fastest.

基本上是一个序号比较只是的需要逐个字符走两个字符串,字符,直到找到一个差异。如果没有找到任何差异,和长度是相同的,其结果为0。如果没有找到任何差异,但长度不相同,较长的字符串被认为是大。如果它的确实的找到一个差异,它可以立即工作,这被认为是大的基础上的字符是在顺序方面大。

Basically an ordinal comparison just needs to walk the two strings, character by character, until it finds a difference. If it doesn't find any differences, and the lengths are the same, the result is 0. If it doesn't find any differences but the lengths aren't the same, the longer string is deemed "larger". If it does find a difference, it can immediately work out which is deemed "larger" based on which character is "larger" in ordinal terms.

要投入是另一种方式。这就像做两的char [] 值之间的明显对比

To put is another way: it's like doing the obvious comparison between two char[] values.

文化敏感的比较具有执行各种曲折的壮举,这取决于你使用精确的文化。对于这样的例子,请参见这个问题。这是很清楚,有更复杂的规则可循可以让这个更慢。

Culture-sensitive comparisons have to perform all kinds of tortuous feats, depending on the precise culture you use. For an example of this, see this question. It's pretty clear that having more complex rules to follow can make this slower.

这篇关于什么是C#中的最快的(内置)比较字符串类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆