2014-10-28 56 views
3

我現在有一類「ArisingViewModel」在其上有20-30左右的屬性將被檢查10000次,當我生成各種數據慢。速度屬性字典比使用switch語句

起初,我不得不檢索沿線的XML字符串中出現的屬性值的方法:

public object GetArisingPropertyValue(string propertyName) 
    { 
     switch (propertyName) 
     { 
      case "name_1": 
       return Name1; 
      case "another_name": 
       return AnotherName; 

      // etc. 
     } 
    } 

但是,這是適合使用屬性字典,以使事情更容易更新,使對於項目的其他部分,生活更容易。所以,我建立了我的屬性字典,像這樣:

private static readonly IDictionary<string, string> PropertyMap; 


    static ArisingViewModel() 
    { 
     PropertyMap = new Dictionary<string, string>(); 

     var myType = typeof(ArisingViewModel); 

     foreach (var propertyInfo in myType.GetProperties(BindingFlags.Instance | BindingFlags.Public)) 
     { 
      if (propertyInfo.GetGetMethod() != null) 
      { 
       var attr = propertyInfo.GetCustomAttribute<FieldNameAttribute>(); 

       if (attr == null) 
        continue; 

       PropertyMap.Add(attr.FieldName, propertyInfo.Name); 
      } 
     } 
    } 

我將屬性應用於任何相關propertys像這樣:

[FieldName("name_1")] 
    public string Name1 
    { 
     get 
     { 
      return _arisingRecord.Name1; 
     } 
    } 

,然後用下面的方法找物業名稱/值:

public static string GetPropertyMap(string groupingField) 
    { 
     string propName; 
     PropertyMap.TryGetValue(groupingField, out propName); 
     return propName; //will return null in case map not found. 
    } 

    public static object GetPropertyValue(object obj, string propertyName) 
    { 
     return obj.GetType().GetProperty(propertyName).GetValue(obj, null); 
    } 

我的問題是,我發現處理是顯著量快速使用舊的switch語句(用一個非常簡單的定時器類測量系統正在多久 - 〜20 SE conds vs〜25秒)。

任何人都可以建議我做錯了什麼,或者改善目前的代碼的任何方式?

+0

戴上* *財產,而不是*屬性名*到字典 – 2014-10-28 14:36:28

+3

反思**是慢**(這裏甚至屬性搜索重複每個接入)。如果在這種情況下是一個問題,只需構建代表字典(而不是屬性名稱):Dictionary 。委託調用比第一種方法慢(如果屬性數量不是很大),但沒有那麼明顯。你也可以嘗試表達式和Reflection.Emit,但是......先做好測量! – 2014-10-28 14:36:30

+0

謝謝,這對我有意義。我會看看Dictionary 解決方案,看看它有多快,如果它仍然很慢,它會返回到交換機! – jimbo 2014-10-28 14:50:48

回答

1

我建議執行從StringTemplate的4(BSD 3-條款許可)的C#端口類似於ObjectModelAdaptor一個類。此功能主要用於模板渲染管道的性能關鍵部分,並且分析表明當前的實現表現良好。

該課程使用合理高效的緩存和調度機制,儘管可以通過使用ConcurrentDictionary並刪除lock語句來改進.NET 4+用戶的性能。

您可能需要更改FindMember的實現,以便使用屬性實現特定於您的屬性的邏輯。