2009-07-06 94 views
1

我正在使用WPF,我正在開發一個複雜的用戶控件,它由一個具有豐富功能的樹組成。 爲此,我使用了View-Model設計模式,因爲有些操作無法直接實現在WPF中。所以,我把IHierarchyItem(這是一個節點,並把它傳遞給這個構造函數來創建一個樹形結構)沒有遞歸/堆棧使用(C#)的樹遍歷?

private IHierarchyItemViewModel(IHierarchyItem hierarchyItem, IHierarchyItemViewModel parent) 
     { 
      this.hierarchyItem = hierarchyItem; 
      this.parent = parent;  

      List<IHierarchyItemViewModel> l = new List<IHierarchyItemViewModel>(); 
      foreach (IHierarchyItem item in hierarchyItem.Children) 
      { 
       l.Add(new IHierarchyItemViewModel(item, this)); 
      } 
      children = new ReadOnlyCollection<IHierarchyItemViewModel>(l); 
     } 

是,此構造需要大約3秒鐘的問題! 200個項目在我的雙核上。 我做任何錯誤或遞歸的構造函數調用是慢? 非常感謝!

+0

確定上面的所有內容都是正確的。問題存在於hierarchyItem.Children中,因爲它耗時太長。 – 2009-07-15 13:28:23

回答

3

樹的遞歸實現應該沒有問題,尤其是對於這樣一小部分的項目。遞歸實現有時候更節省空間,而且時間效率稍低,但代碼清晰度通常彌補了這一點。

對你來說,對你的構造函數執行一些簡單的分析將會很有用。使用以下建議之一:http://en.csharp-online.net/Measure_execution_time您可以指出每件作品需要多長時間。

有可能一件特別是需要很長時間。無論如何,這可能會幫助你縮小你真正花時間在哪裏。

+0

謝謝,我會試試這個片段..你可能是對的,它不能再花那麼長時間,問題可能在特定項目的某個地方。 – 2009-07-06 13:42:34

+0

int this line:foreach(hierarchyItem.Children中的IHierarchyItem項) hierarchyItem.Children花了太長時間。 – 2009-07-15 13:29:08

4

好的我自己找到了一個非遞歸的版本,儘管它使用了堆棧。 它遍歷整棵樹:

Stack<MyItem> stack = new Stack<MyItem>(); 

stack.Push(root); 

while (stack.Count > 0) 
{ 
    MyItem taken = stack.Pop(); 

    foreach (MyItem child in taken.Children)     
     stack.Push(MyItem);      

}