异常处理是个十分深奥的主题,这里只是浅论其对C++性能的影响。
在VC++中,有多个异常处理模式,三个最重要:
No exception handling (无异常处理)
C++ only (C++语言异常处理)
C++ 加SEH (C++语言加windows 结构异常处理机制)
异常处理每增加一个级别,都要付出时空上的代价。我们从下面简单的C++例子着手,分析异常处理的原理及其性能:
// simple class class MyAppObject { public: MyAppObject(int id) : _myID(id) {} ~MyAppObject(); int _myID; void DoSomething(int throwWhat) ; }; // can throw 2 different exception void MyAppObject::DoSomething(int throwWhat) { printf("MyAppObject::DoSomething called for '%d'\n", _myID); switch (throwWhat) { case 0: break; case 1: this->_myID /= 0; // exception 1 break; case 2: throw SimpleString("error!"); // exception 2 break; } } // Test exception for the above class void TestMyAppObject() { printf("before try”); try // line1 { printf("in try”); MyAppObject so = 1; // line2 SimpleString ss("test ex point one"); // line3 so.DoSomething(1); // line4 printf("so::ID called for '%d'\n", so._myID); MyAppObject so2 = 2; // line5 printf("so2::ID called for '%d'\n", so2._myID); so2.DoSomething(0); // line6 } catch(const SimpleString &e) // line7 { //printf("something happened: %s \n", e); } catch(...) //line8 { //printf("something happened: %s \n", "SEH"); } } |
第一步,我们先选择“no exception”,并将上面line1,line7,line8注释掉。代码的size是:
Exe
Obj
32,256 bytes
20,931 bytes
然而因为line4引入一个“除0”异常,我们的程序非正常地停止了工作。这并非什么大的灾难。但是如果这是关键的服务器程序,这样的结果肯定不能为客户接受。