[C#.NET] 動態陣列處理 - StringCollection 類別與 List 類別的效能比較

  • 18920
  • 0
  • C#
  • 2013-07-05

[C#.NET] 動態陣列處理 - StringCollection 類別與 List 類別的效能比較

在上篇文章[C#.NET][VB.NET] 一般集合 - StringCollection 集合 類別簡介,有網友提到StringCollection 類別比List<string>類別效能差;但是在微軟的70-536的考試用書裡有提到,若是純字串的集合建議使用StringCollection 類別,當時只謹記在心中並未實際的比較過,所以今日就來實作一下比較結果。若想要知道ArrayList的效能如何請參考[C#.NET][VB.NET] ArrayList 與 List<> 執行效能比較


System.Collections.Generic.List<string> lst = new List<string>();
System.Collections.Specialized.StringCollection sc = new StringCollection();
public List<string> listAddMethod()
{
    for (int i = 0; i < 10000; i++)
    {
        lst.Add(i.ToString());
    }
    return lst;
}
public StringCollection scAddMethod()
{
    for (int i = 0; i < 10000; i++)
    {
        sc.Add(i.ToString());
    }
    return sc;
}

結果如下,70-536的考試用書果然沒騙我。

image

接著我想看看它們在動態移除的效能,先再建構子增加集合。


public Form1()
{
    InitializeComponent();
    //
    listAddMethod();
    scAddMethod();
}

public List<string> listCutMethod()
{
    for (int i = 10000; i >= 0; i--)
    {
        lst.Remove(i.ToString());
    }
    return lst;
}
public StringCollection scCutMethod()
{
    for (int i = 10000; i <= 0; i--)
    {
        sc.Remove(i.ToString());
    }
    return sc;
}

 

這次還是由StringCollection 類別勝出。

image

 

結論:

由上述簡單的程式碼即能明瞭,在純字串的集合,StringCollection 類別處理起來的效能是優於List<string>泛型集合的,因此若是我們單純要處理字串集合,別忘了優先考慮StringCollection 類別喔,那如果是StringDictionary類別Dictionary<string,string>該選哪個呢?..如果是同樣的條件都是字串的話我會選StringDictionary類別,不信的話,就自己再動手測測吧。

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo