C# 中的异常有多昂贵?只要堆栈不深,它们似乎并不会非常昂贵;然而我读到了相互矛盾的报道。
有没有没有被反驳的明确报告?
读到异常在性能方面代价高昂后,我编写了一个简单的测量程序,与该程序非常相似乔恩·斯基特 多年前发表 https://web.archive.org/web/20190303182328/http://yoda.arachsys.com/csharp/exceptions.html。我在这里提到这一点主要是为了提供更新的数字。
程序处理一百万个异常的时间低于 29914 毫秒,相当于每毫秒 33 个异常。这足够快,足以使异常成为大多数情况下返回代码的可行替代方案。
但请注意,使用返回码而不是异常时,同一程序的运行时间不到一毫秒,这意味着异常比返回代码至少慢 30,000 倍。正如所强调的里科·马里亚尼 https://learn.microsoft.com/en-us/archive/blogs/ricom/the-true-cost-of-net-exceptions-solution这些数字也是最小数字。在实践中,抛出和捕获异常将花费更多时间。
在配备 Intel Core2 Duo T8100 @ 2.1 GHz、发行版 .NET 4.0 的笔记本电脑上测量不在调试器下运行(这会使速度变慢)。
这是我的测试代码:
static void Main(string[] args)
{
int iterations = 1000000;
Console.WriteLine("Starting " + iterations.ToString() + " iterations...\n");
var stopwatch = new Stopwatch();
// Test exceptions
stopwatch.Reset();
stopwatch.Start();
for (int i = 1; i <= iterations; i++)
{
try
{
TestExceptions();
}
catch (Exception)
{
// Do nothing
}
}
stopwatch.Stop();
Console.WriteLine("Exceptions: " + stopwatch.ElapsedMilliseconds.ToString() + " ms");
// Test return codes
stopwatch.Reset();
stopwatch.Start();
int retcode;
for (int i = 1; i <= iterations; i++)
{
retcode = TestReturnCodes();
if (retcode == 1)
{
// Do nothing
}
}
stopwatch.Stop();
Console.WriteLine("Return codes: " + stopwatch.ElapsedMilliseconds.ToString() + " ms");
Console.WriteLine("\nFinished.");
Console.ReadKey();
}
static void TestExceptions()
{
throw new Exception("Failed");
}
static int TestReturnCodes()
{
return 1;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)