问题描述
我正在与一些代码,返回一个代码,以指示它们是用户类型工作(例如,A,B,C,D等)。每个代码对应一个特定的角色和/或范围(例如,在整个应用程序或只为对象正在制定)。
I'm working with some code that returns a code to indicate the type of user that they are (e.g. "A", "B", "C", "D", etc.). Each code corresponds to a specific role and/or scope (e.g. across the entire application or just for the object being worked on).
在一些代码,我在寻找在我看到的调用来检查,如果用户的密码是为了让他们执行一些动作的几个之一。所以,我看到这样的呼叫:
In some code that I'm looking at, I see calls to check if the user's code is one of several in order to allow them to perform some action. So I see calls like:
//"B" would come from the database
string userCode = "B";
//some more work...
//if the user's code is either A or C...
if("AC".IndexOf(userCode) >= 0) {
//do work that allows the user to progress
} else {
//notify user they can't do this operation
}
这是执行此检查的有效途径?有没有更有效的方法?
Is this an efficient way of performing this check? Are there more efficient ways?
在此先感谢!
推荐答案
综观去编译代码包含()
,它只是调用的IndexOf()
与 StringComparison.Ordinal
,所以我会说的IndexOf()
是最有效的(由一个非常小的头发),如果以同样的方式使用我(序),因为它少了一个方法调用,但包含()
是更具可读性,因此更容易维护...
Looking at the de-compiled code for Contains()
, it just calls IndexOf()
with StringComparison.Ordinal
, so I'd say IndexOf()
is most efficient (by a very small hair) i if used in the same way (Ordinal) since it has one less method call, but Contains()
is more readable and therefore more maintainable...
public bool Contains(string value)
{
return (this.IndexOf(value, StringComparison.Ordinal) >= 0);
}
由于在所有的事情,我会用什么更好的可读性和可维护性然后去性能鸡蛋里挑骨头。只有做到当你知道有在这一点上的瓶颈微型优化
As in all things, I'd go with what's more readable and maintainable then splitting hairs on performance. Only do micro-optimization when you know there's a bottleneck at this point.
更新:超过一百万的迭代:
UPDATE: Over 1,000,000 iterations:
- 包含(值) - 花130MS
- 的IndexOf(值,StringComparison.Ordinal) - 128了毫秒
因此,大家可以看到,非常,非常接近相同。再一次,去更重要的是维护
So as you can see, very, very NEAR same. Once again, go with what's more maintainable.
更新2 :如果您的代码始终是一个单个字符(而不是1字符的字符串) ,的IndexOf()是速度快:
UPDATE 2: If your code is always a single char (not a 1-char string), IndexOf() is faster:
- 包含(char值) - 拿了94毫秒
- 的IndexOf (char值) - 用了16毫秒
如果你知道你的字符代码始终是一个单个字符,它是关于一个数量级更快地使用的IndexOf()
对于char参数。
If you know your char codes are always a single char, it is about an order of magnitude faster to use IndexOf()
with a char argument.
这是因为包含( char值)
是一个扩展方法关闭的IEnumerable<的; T>
,而不是串的第一类方法
。
This is because Contains(char value)
is an extension method off of IEnumerable<T>
and not a first class method of string
.
的但的再次〜100毫秒超过100万次迭代是真的,真的,完全可以忽略。
But once again ~100 ms over 1,000,000 iterations is really, truly, quite negligible.
这篇关于这是搜索字符串的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!