2013-04-11 23 views
-1

我很想知道,以下哪種方法更適合?按鍵選擇字典元素查找的方法?

//Dictionary dic<string, int>; 

int getElementByKey1(string key) 
{ 
    if(dic.ContainsKey(key))  //Look-up 1 
     return dic[key];  //Look-up 2 in case of a "hit" 

    return null; 
} 

int getElementByKey2(string key) 
{ 
    try 
    { 
     return dic[key];  //Single look-up in case of a "hit" 
    } 
    catch 
    { 
     return null;   //Exception in case of a "miss" 
    } 
} 
+2

馬爾辛 - 給了一個很好的解決方案,以你的問題。我只想做一個側面說明,使用try/catch做決策總是一個不好的主意,因爲它慢得多。只能使用try/catch來捕獲意外的異常。 – Quintium 2013-04-11 20:31:38

+0

@Quintium:「try/catch」塊的用法是什麼讓它變慢,或者只有在拋出異常時變得緩慢? – ahmd0 2013-04-11 20:32:59

+2

@ ahmd0僅當實際拋出異常時。 – MarcinJuraszek 2013-04-11 20:41:44

回答

6

如何,第三個,使用TryGetValue()方法:

int getElementByKey3(string key) 
{ 
    int value; 
    dic.TryGetValue(key, out value) 
    return value; 
} 

順便說一句:你的方法是無效的,因爲你不能從聲明爲int方法返回null

應宣佈爲int?,而不是允許null值:

int? getElementByKey3(string key) 
{ 
    int value; 
    if(dic.TryGetValue(key, out value)) 
     return value; 

    return null; 
} 

我認爲這將是最好的之一。但是如果我必須從你中選擇兩個建議的方法,我會選擇第一個 - 第二個看起來更快,但是當拋出異常時它不會那麼快,因爲它必須被處理,並且它需要一定量的工作。

+0

哦,非常好。我沒有意識到這種方法存在。非常感激。 (PS。我沒有意識到,在我原來的帖子中,'int'不能'null'...哎呀。) – ahmd0 2013-04-11 20:25:28

0

無。更好的去:

string result = null; 
if (dic.TryGetValue(key, out result) 
{ 
    // don't know, maybe log it somewhere or sth? 
} 

return result; 
1

可以使用StopWatchers測試的執行時間,第一,把一些價值上解釋:

Random r = new Random(); 
    for (int i = 0; i < 10000; i++) 
    { 
     d.Add(Guid.NewGuid().ToString(), r.Next()); 

     //put some manual key for search later 
     if (i == 9001) 
      d.Add("it's over", 9000); 
    } 

,然後做出一些使用搜索StopWatchers(使用System.Diagnostics程序) :

  • 首先測試中,當存在值(不拋出異常):

    Stopwatch st1 = new Stopwatch(); 
    st1.Start(); 
    int getKey1 = getElementByKey1("it's over"); 
    st1.Stop(); 
    
    Stopwatch st2 = new Stopwatch(); 
    st2.Start(); 
    int getKey2 = getElementByKey2("it's over"); 
    st2.Stop(); 
    

結果在我的電腦:

Time spent on first search: 00:00:00.0002738 
Time spent on second search: 00:00:00.0001169 

所以,第一個是在返回值之前,因爲驗證if (d.ContainsKey(key))慢。

  • 第二次測試,在不存在的值(拋出異常,如:int getKey1 = getElementByKey1("nevermind");):

結果:

Time spent on first search: 00:00:00.0002331 
Time spent on second search: 00:00:00.0822669 

正如你所看到的,扔exceptionskillsperformance當拋出異常。

注意:您不能返回INT的方法返回null,所以我用return 0;

+0

好的測試。謝謝。 – ahmd0 2013-04-11 22:22:09