Avatar ·

为什么 try-catch 会加速我的 C# 代码执行?

大家好。我是一名初学 C# 的开发者,遇到了一个非常奇怪的行为。我有一个处理数字数组的方法。我决定用 Stopwatch 测试性能,发现带有 try-catch 的版本比没有它的版本运行得更快!以下是简化代码: ```csharp // 慢速版本(无 try-catch) public static void ProcessWithoutTryCatch(int[] data) { for (int i = 0; i < data.Length; i++) { if (data[i] > 0 && data[i] < 100) { // 一些简单的逻辑 int result = data[i] * 2; } } } // 快速版本(带 try-catch) public static void ProcessWithTryCatch(int[] data) { for (int i = 0; i < data.Length; i++) { try { if (data[i] > 0 && data[i] < 100) { int result = data[i] * 2; } } catch (Exception ex) { // 什么都不做 } } } ``` 我运行了