C# 当密钥基于多个标识属性时,优化字典以进行比较

C# 当密钥基于多个标识属性时,优化字典以进行比较,c#,performance,dictionary,C#,Performance,Dictionary,我有以下代码: if (!this._masterAccountDefinitions.ContainsKey( outletName.ToLower(CultureInfo.CurrentCulture) + "/" + officeName.ToLower(CultureInfo.CurrentCulture)) ) { //Add new item to list } 本质上,字典是由门店名称和办公室名称组合而成的。这段代码将被广泛调用,它似乎只是做了

我有以下代码:

if (!this._masterAccountDefinitions.ContainsKey(
     outletName.ToLower(CultureInfo.CurrentCulture) + "/" +
     officeName.ToLower(CultureInfo.CurrentCulture))
   ) {
     //Add new item to list
}

本质上,字典是由门店名称和办公室名称组合而成的。这段代码将被广泛调用,它似乎只是做了一些非常苛刻的字符串转换。我正在寻找一种比简单地连接字符串值更有效的字典键控方法的建议。

你有证据证明这会导致问题吗?我不希望它会引起任何问题,而且我想不出任何真正有帮助的东西,除非你想输入一个名字来获得一个“子字典”这是由另一个名字组成的——但这会使代码更难看,在大多数情况下,我看不到它能提高性能。

假设效率是指性能——很难推测将字符串串接为键的方法会产生更好的性能——您必须首先了解瓶颈是

然而,我想到的一个想法是创建一个单独的类来表示键,并重写它的
Equals()
GetHashCode()
方法。他们将在
Equals()
中使用不区分大小写的比较,在
GetHashCode()
中使用散列码的异或

这可能有助于避免将字符串转换为小写的成本,并消除连接它们的需要。但是,它引入了使用自定义类对集合进行键控的成本,该类需要为字典中存储的每个项实例化。此外,哈希算法可能不如对串联字符串进行哈希优化(即导致更多冲突)

我强烈建议您在转换到更复杂的替代方案之前,花一些时间分析代码,以确定在您的情况下仅仅串联字符串是不够有效的

以下是一个非常粗糙的原型:

public class AccountKey
{
   private readonly string m_OutletName;
   private readonly string m_OfficeName;

   public AccountKey( string outlet, string office )
   {
      m_OutletName = outlet;
      m_OfficeName = office;
   }

   public string OutletName { get { return m_OutletName; } }
   public string OfficeName { get { return m_OfficeName; } }

   public override bool Equals( object otherKey )
   { 
      AccountKey otherAccountKey = otherKey as AccountKey;      
      if( otherAccountKey == null )
         return false;

      // uses Compare( s1, s2, ignoreCase ) overload - which assumes current culture
      // alternative culture can be passed in as another parameter after ignore case
      // uses short-circuit and to avoid comparing both strings if one already differs
      // you could order these based on your domain knowledge more optimally - for
      // example if Offices vary more frequently than Outlet, make that compare first.
      return String.Compare( m_OutletName, otherAccountKey.OutletName, true ) == 0 &&
             String.Compare( m_OfficeName, otherAccountKey.OfficeName, true ) == 0;
   }

   public override int GetHasCode()
   {
      // this may not be optimal, but it's a starting point
      return OutletName.GetHashCode() ^ OfficeName.GetHashCode();
   }
}

您是否做了一些分析,看看这是否真的会导致性能问题?除非我确定这是一个问题,否则我不会对它进行优化。我主要关心的是通过串联和ToLower()函数不断创建不同的字符串。我想我希望有一种比重建字符串更有效的方法。