TITLE: bjarne on exception efficiency (Newsgroups: comp.lang.c++, 28 Apr 97) KHAIROUTDINOV: Marat Khairoutdinov (marat@rossby.uoknor.edu) > : The main difference is that new calls an object's constructor, and > : delete calls its destructor, while malloc() and free() ain't > : do that. New does not return NULL in the case of failing to > : allocate the memory, but rather throws an exception, according > : the new draft of the C++ ANSI. Many compilers don't support the latter > : yet. > ADELSBERGER: jja@ultra7.cc.umr.edu (John Adelsberger) > If new throws an exception instead of returning NULL, then C++ is now > truly useless for anything but Windoze trash. No respectable systems > programmer would use the slow, bulky, kludgy C++ exception system; > imagine if every memory allocation failure in a system object raised > an exception that is essentially an O(N^?) operation, where the ? is > dependent on the context. This is utter garbage and totally defeats > Bjarne's original goal of never adding a feature that has runtime > overhead. > I disliked C++ prior to hearing this. Now I disdain it; it is trash, > useless for anything but writing games and first semester college > programming exercises, and maybe the occasional slow, bloated office > suite from Microsloth. STRUSTRUP: bs@research.att.com (Bjarne Stroustrup) Feel better now? There is nothing in the C++ exception mechanism that needs to be bloated or slow. In fact, it has been implemented so that the worst-case cost of throwing an exception is O(log(n)) where n is the number of exception handlers in the program. Given that most local tests are eliminated, that's FAST. Actually, the performance of a system in the case where an exception is thrown shouldn't be important because exceptions ought to be exceptional. My ideal is that the cost of a try block is 0 while the cost of an actual throw is 100*the_cost_of_a_function_call. This meets my criteria that you pay only for what you explicitly use. My impression is that current PC implementations are suboptimal because the cost of a try-block is non-zero while the const of an actual throw is O(n) where n is the number of function calls between the function throwing and the function catching. However, this makes catching an exception close to the throw point efficient (which seems to be what you want). The actual cost seems to be changing with each release of a compiler. For people who, for one reason or another, cannot live with memory exhaustion throwing exceptions, "new(nothrow) X;" returns 0 as ever. It is, however, not the recommended way of allocating objects on the free store (heap).