【发布时间】:2013-04-11 20:22:30
【问题描述】:
我想知道,在速度方面,以下哪种方法更可取?
//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"
}
}
【问题讨论】:
-
Marcin 为您的问题提供了很好的解决方案。我只是想说明一下,使用 try/catch 进行决策总是一个坏主意,因为它要慢得多。仅使用 try/catch 捕获意外异常。
-
@Quintium:是使用
try/catch块使其变慢,还是只有在抛出异常时才会变慢? -
@ahmd0 仅在实际抛出异常时。
-
@MarcinJuraszek:再次感谢。只是出于好奇,如果抛出异常,我们在谈论多少“浪费”?
-
@ahmd0 - 是的,很抱歉通过它总是很慢。不,正如 Marcin 所说,只有在被抛出时。但是作为一个例子,如果你知道有机会,最好再次检查 NULL,而不是捕获 NullException
标签: c# .net dictionary