我正在构建一个项目,其中配置文件将作为字典加载。为了防止配置无效,我只添加了一个try catch框架。但我注意到,当异常抛出时,会出现戏剧性的性能下降。所以我做了个测试:
var temp = new Dictionary<string, string> {["hello"] = "world"};
var tempj = new JObject() {["hello"]="world"};
Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 100; i++)
{
try
{
var value = temp["error"];
}
catch
{
// ignored
}
}
sw.Stop();
Console.WriteLine("Time cost on Exception:"+sw.ElapsedMilliseconds +"ms");
sw.Restart();
for (int i = 0; i < 100; i++)
{
var value = tempj["error"]; //equivalent to value=null
}
Console.WriteLine("Time cost without Exception:" + sw.ElapsedMilliseconds + "ms");
Console.ReadLine();结果是:
例外情况下的时间成本:1789 on 时间成本毫无例外:0MS
这里的JObject是从Newtownsoft.Json中提取的,它不会在找不到键时抛出异常,而不是字典。
所以我的问题是:
谢谢!
发布于 2017-06-12 10:29:21
使用Dictionary.TryGetValue可以完全避免示例代码中的异常。最昂贵的部分是try .. catch。
如果您无法避免异常,那么您应该使用不同的模式来执行循环中的操作。
而不是
for ( i = 0; i < 100; i++ )
try
{
DoSomethingThatMaybeThrowException();
}
catch (Exception)
{
// igrnore or handle
}它将为每个步骤设置try .. catch,无论异常是否已引发,请使用
int i = 0;
while ( i < 100 )
try
{
while( i < 100 )
{
DoSomethingThatMaybeThrowException();
i++;
}
}
catch ( Exception )
{
// ignore or handle
i++;
}只有在抛出异常时才会设置新的try .. catch。
BTW
我不能像您描述的那样复制您代码的大规模减速。.net小提琴
https://stackoverflow.com/questions/44496000
复制相似问题