尝试捕捉性能 c#

fil*_*pot 1 c# performance try-catch

我对 try catch 的了解有限。但我想知道它是否可以用来获得性能。

例如,我正在创建这个体素引擎,其中一个函数是这样的:

Block GetBlockInChunk(Vector Position){
    if(InBound(Position)){
        return Database.GetBlock();
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

这里它必须检查给定位置的边界,使用try catch,然后你可以删除它们吗?

Block GetBlockInChunk(Vector Position){
    try{
        return Database.GetBlock();
    }
    catch{
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

我觉得这可能是可怕的做法,但我很好奇。

Abi*_*n47 6

我在上述评论中提供的链接显示了为什么当 if 语句会阻止抛出异常时不应该使用 try-catch 的描述,但为了根据实际数字显示性能,我编写了这个快速的小测试程序。

Stopwatch watch = new Stopwatch();

int[] testArray = new int[] { 1, 2, 3, 4, 5 };
int? test = null;

watch.Start();
for (int i = 0; i < 10000; i++)
{
    try
    {
        testArray[(int)test] = 0;
    }
    catch { }
}
watch.Stop();

Console.WriteLine("try-catch result:");
Console.WriteLine(watch.Elapsed);
Console.WriteLine();

watch.Restart();
for (int i = 0; i < 10000; i++)
{
    if (test != null)
        testArray[(int)test] = 0;
}
watch.Stop();

Console.WriteLine("if-statement result:");
Console.WriteLine(watch.Elapsed);
Run Code Online (Sandbox Code Playgroud)

程序的结果是这样的:

try-catch result:
00:00:32.6764911

if-statement result:
00:00:00.0001047
Run Code Online (Sandbox Code Playgroud)

如您所见,try-catch 方法在捕获异常时引入了大量开销,在我的机器上完成 10,000 个周期需要 30 多秒。另一方面,if 语句运行得如此之快,以至于它基本上是瞬时的。与 try-catch 相比,这是大约 3,000,000% 的性能改进。

(这不是一个严格的基准测试,并且有多种方法可以编写它并以不同的方式运行它以获得更精确的数字,但这应该会让您很好地了解使用 if 语句比尽可能尝试捕获。)

  • *堆栈跟踪*(当抛出异常时)是非常耗时的操作(与简单的“if”相比) (2认同)