C# 的例外處理,若無 catch 到例外,則有無 try catch 幾乎不影響效能。若有 catch 到例外,則對效能會有極大的影響。
using System;
using System.Diagnostics;
namespace ConsoleApplication1 {
class Program {
static void Foo() {
try { throw new InvalidOperationException(); } catch { }
}
static void Main(string[] args) {
const Int32 REPEAT = 1000000;
Stopwatch stopwatch = Stopwatch.StartNew();
for(Int32 i=0; i < REPEAT; i++) { Foo(); }
stopwatch.Stop();
Console.WriteLine(((Double)REPEAT)/(((Double)(stopwatch.ElapsedMilliseconds)) / 1000.0));
Console.ReadKey();
}
}
}
上面的 C# 程式,編譯成 Release 版,在我的機器上輸出為 72259。同樣的程式用 C++ 寫,其實也沒有快多少:
void Foo() {
try { throw 0; } catch(...) {}
}
int main(int argc, char* argv[]) {
const int REPEAT = 1000000;
DWORD from = ::timeGetTime();
for(int i=0; i < REPEAT; i++) { Foo(); }
DWORD to = ::timeGetTime();
std::cout << double(REPEAT)/(double(to - from)/1000.0) << std::endl;
std::cin.get();
return 0;
}
上面的 C++ 程式的輸出是 125802。
沒有留言:
張貼留言