Volunteer .NET Evangelist

A well oiled machine can’t run efficiently, if you grease it with water.
  首页  :: 联系 :: 订阅 订阅  :: 管理

Faster String Comparison

Posted on 2006-01-22 00:24  Sheva  阅读(324)  评论(0编辑  收藏  举报
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:
public bool Equals(string 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;
}

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.