I wrote some code for testing the impact of try-catch, but seeing some surprising results.
(我写了一些代码来测试try-catch的影响,但看到了一些令人惊讶的结果。)
static void Main(string[] args)
{
Thread.CurrentThread.Priority = ThreadPriority.Highest;
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
long start = 0, stop = 0, elapsed = 0;
double avg = 0.0;
long temp = Fibo(1);
for (int i = 1; i < 100000000; i++)
{
start = Stopwatch.GetTimestamp();
temp = Fibo(100);
stop = Stopwatch.GetTimestamp();
elapsed = stop - start;
avg = avg + ((double)elapsed - avg) / i;
}
Console.WriteLine("Elapsed: " + avg);
Console.ReadKey();
}
static long Fibo(int n)
{
long n1 = 0, n2 = 1, fibo = 0;
n++;
for (int i = 1; i < n; i++)
{
n1 = n2;
n2 = fibo;
fibo = n1 + n2;
}
return fibo;
}
On my computer, this consistently prints out a value around 0.96..
(在我的电脑上,这始终打印出一个大约0.96的值。)
When I wrap the for loop inside Fibo() with a try-catch block like this:
(当我使用try-catch块在Fibo()中包装for循环时,如下所示:)
static long Fibo(int n)
{
long n1 = 0, n2 = 1, fibo = 0;
n++;
try
{
for (int i = 1; i < n; i++)
{
n1 = n2;
n2 = fibo;
fibo = n1 + n2;
}
}
catch {}
return fibo;
}
Now it consistently prints out 0.69... -- it actually runs faster!
(现在它一直打印出0.69 ...... - 它实际上运行得更快!)
But why? (但为什么?)
Note: I compiled this using the Release configuration and directly ran the EXE file (outside Visual Studio).
(注意:我使用Release配置编译它并直接运行EXE文件(在Visual Studio外部)。)
EDIT: Jon Skeet's excellent analysis shows that try-catch is somehow causing the x86 CLR to use the CPU registers in a more favorable way in this specific case (and I think we're yet to understand why).
(编辑: Jon Skeet的优秀分析表明try-catch在某种程度上导致x86 CLR在这种特定情况下以更有利的方式使用CPU寄存器(我认为我们还没理解为什么)。)
I confirmed Jon's finding that x64 CLR doesn't have this difference, and that it was faster than the x86 CLR. (我确认Jon发现x64 CLR没有这个区别,并且它比x86 CLR更快。)
I also tested using int
types inside the Fibo method instead of long
types, and then the x86 CLR was as equally fast as the x64 CLR. (我还在Fibo方法中使用int
类型而不是long
类型进行了测试,然后x86 CLR和x64 CLR一样快。)
UPDATE: It looks like this issue has been fixed by Roslyn.
(更新:看起来这个问题已由Roslyn修复。)
Same machine, same CLR version -- the issue remains as above when compiled with VS 2013, but the problem goes away when compiled with VS 2015. (相同的机器,相同的CLR版本 - 在使用VS 2013编译时问题仍然如上所述,但在使用VS 2015编译时问题就消失了。)
ask by Eren Ers?nmez translate from so