开发者

Alternatives to String.Compare for performance

I've used a profiler on my C# application and realised that String.Compare() is taking a lot of time overall: 43% of overall time with 124M hits

I'm comparing relatively small string: from 4 to 50 chars. What would you recommend to replace it with in terms of performance??

UPD: I only need to decide if 2 strings are the same or not.开发者_开发知识库 Strings can be zero or "". No cultural aspect or any other aspect to it. Most of the time it'll be "4578D" compared to "1235E" or similar.

Many thanks in advance!


It depends on what sort of comparison you want to make. If you only care about equality, then use one of the Equals overloads - for example, it's quicker to find that two strings have different lengths than to compare their contents.

If you're happy with an ordinal comparison, explicitly specify that:

int result = string.CompareOrdinal(x, y);

An ordinal comparison can be much faster than a culture-sensitive one.

Of course, that assumes that an ordinal comparison gives you the result you want - correctness is usually more important than performance (although not always).

EDIT: Okay, so you only want to test for equality. I'd just use the == operator, which uses an ordinal equality comparison.


You can use different ways of comparing strings.

String.Compare(str1, str2, StringComparison.CurrentCulture) // default
String,Compare(str1, str2, StringComparison.Ordinal) // fastest

Making an ordinal comparison can be something like twice as fast as a culture dependant comparison.

If you make a comparison for equality, and the strings doesn't contain any culture depenant characters, you can very well use ordinal comparison.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜