在C#中字符串比较性能 [英] String comparison performance in C#

查看:405
本文介绍了在C#中字符串比较性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有多种方式来比较字符串。通过这样一种方式在另一个有性能提升?

There are a number of ways to compare strings. Are there performance gains by doing one way over another?

我总是选择比较像这样的字符串:

I've always opted to compare strings like so:

string name = "Bob Wazowski";
if (name.CompareTo("Jill Yearsley") == 0) {
    // whatever...
}

不过,我觉得很少有人这样做,如果有什么,我看到更多的人只是在做直==比较,这在我的知识是比较字符串的最糟糕的方式。难道我错了吗?

But I find few people doing this, and if anything, I see more people just doing a straight == comparison, which to my knowledge is the worst way to compare strings. Am I wrong?

此外,它使怎么一比较字符串LINQ查询中的区别?比如,我喜欢做如下:

Also, does it make a difference in how one compares strings within LINQ queries? For example, I like to do the following:

var results = from names in ctx.Names
              where names.FirstName.CompareTo("Bob Wazowski") == 0
              select names;

但同样,我看到几个人在做字符串比较像这样在他们的LINQ查询。

But again, I see few people doing string comparisons like so in their LINQ queries.

推荐答案

据反射

"Hello" == "World"

是相同的

String.Equals("Hello", "World");

基本上确定它们是否相同的参考对象时,如果其中的任一为空,这将是一个自动假如果为空,而另一个不是,然后每个字符在不安全的循环相比较。因此,它不关心文化规则可言,这通常不是什么大不了的事。

which basically determines if they are the same reference object, if either of them is null, which would be an automatic false if one was null and the other was not, and then compares each character in an unsafe loop. So it doesn't care about cultural rules at all, which usually isn't a big deal.

"Hello".CompareTo("World") == 0

是相同的

CultureInfo.CurrentCulture.CompareInfo.Compare("Hello", "World", CompareOptions.None);

这基本上是相反的,只要功能。它考虑到文化,编码,和一切与字符串上下文。

This is basically the opposite as far as functionality. It takes into consideration culture, encoding, and everything else with the string in to context.

所以,我猜想, String.CompareTo是一对夫妇的幅度比相等运算符

为您的LINQ这并不重要,如果你正在使用LINQ到SQL关系,因为两者会产生相同的SQL

as for your LINQ it doesn't matter if you are using LINQ-to-SQL because both will generate the same SQL

var results = from names in ctx.Names
          where names.FirstName.CompareTo("Bob Wazowski") == 0
          select names;

SELECT [name fields]
FROM [Names] AS [t0]
WHERE [t0].FirstName = @p0

所以你真的没有赢得任何东西LINQ到SQL只是难以阅读code和EX pressions的可能更多的分析。如果你只是使用LINQ的标准阵列东西,那么规则,我提出了上述申请。

so you really aren't gaining anything for LINQ-to-SQL except harder to read code and probably more parsing of the expressions. If you are just using LINQ for standard array stuff then the rules I laid out above apply.

这篇关于在C#中字符串比较性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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