string.Equals的静态方法和实例方法哪个更快
比较string是否相等可以使用静态方法String.Equals(), 也可以调用字符串的实例方法, 用reflector察看mscorlib.dll
–Instance Equals method implementation:
<.net 2.0.50727>
public bool Equals(string value)
{
if ((value == null) && (this != null))
{
return false;
}
return string.EqualsHelper(this, value);
}
<.net 1.1>
[MethodImpl(MethodImplOptions.InternalCall)]
public extern bool Equals(string value);
An internal call is a call to a method implemented within the common language runtime itself.
–Static Equals method implementation:
<.net 2.0.50727>
public static bool Equals(string a, string b)
{
if (a == b)
{
return true;
}
if ((a != null) && (b != null))
{
return string.EqualsHelper(a, b);
}
return false;
}
<.net 1.1>
public static bool Equals(string a, string b)
{
if (a == b)
{
return true;
}
if ((a != null) && (b != null))
{
return a.Equals(b);
}
return false;
}
[*]读EqualsHelper的代码,可以看看MS是怎么比字符串的.
可以看到,静态方法会先比较refrence,如果事先知道字符串相等的可能性较大,使用静态方法会快那么一点点.
