As we all know that when comparing strings for equality, you can actually optimize your code a little bit by comparing the reference first, but String's instance Equals method and static version of Equals method performs differently in this regard:
instance Equals method implementation:
static Equals method implementation:
So we can see that static Equals method compares the reference first, if it fails, then performs the ordinal string comparison next, on contrary instance Equals method directly moves to the ordinal string comparison operation, so when comparing strings for equality, using the static Equals method rather than instance Equals method can improve your application's performance, at least, this holds true for the current version of .NET Framework(aka .NET Framework v2.0.50727), probably this problem can be solved in the future version of .NET framework.
instance Equals method implementation:
public bool Equals(string value)
{
if ((value == null) && (this != null))
{
return false;
}
return string.EqualsHelper(this, value);
}
{
if ((value == null) && (this != null))
{
return false;
}
return string.EqualsHelper(this, value);
}
static Equals method implementation:
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;
}
{
if (a == b)
{
return true;
}
if ((a != null) && (b != null))
{
return string.EqualsHelper(a, b);
}
return false;
}
So we can see that static Equals method compares the reference first, if it fails, then performs the ordinal string comparison next, on contrary instance Equals method directly moves to the ordinal string comparison operation, so when comparing strings for equality, using the static Equals method rather than instance Equals method can improve your application's performance, at least, this holds true for the current version of .NET Framework(aka .NET Framework v2.0.50727), probably this problem can be solved in the future version of .NET framework.
![](http://c.spaces.msn.com/CollectionWebService/c.gif?space=shevaspace&page=RSS%3a+Faster+String+Comparison&referrer=)
![](c.msn.com/c.gif?NC=31263&NA=1149&PI=88469&RF=&DI=3919&PS=85545&TP=spaces.msn.com>1=shevaspace%3b2052)