   C++, exceptions and performance
  Hello GDnet !Yeah I'm one of those newbies who believe they can write a lightning-fast 3D engine getting rid of all hi-levels features that C++ offers (who said STL ? ^^) Ok, but now this one is about C++ Exceptions !I've read many different opinions about them...- On the on hande many say that it is a must-have, that it increase code quality etc. I do agree with that for I have used them in java and know how usefull and powerfull there are.- On the other hand, I've read quite a few serious and reliable papers/book which mention that exception handling has a high performance cost and that it should be disabled form the compiler (I'm using VC++ Express btw)Both opinions are indeed not incompatible with each other, but I thought than one might be "more true" that the other. The question is which one ? :)I hoped some peoples who had had experience with exceptions in a performance critical application (if I were developping an office application I would bother speed issues and use exception without hesitating) could forward me their knowledge and wisdom.Do you think it's better to disable them ? (because I believe that one can get away without using exceptions and do *almost* as well as if using them, but is that worst the pain ?)Thanks in advance,JantaPS: ok ok, I will use STL :)   
Quote:Original post by jantaDo you think it's better to disable them ?no! it's true that there's a decent amount of overhead with exceptions, but don't go and disable them. c++ exceptions should only be used for exceptional cases. a critical error in a class contructor is a perfect example. typically in c++ you want to use c-like error checking, like checking return codes to see if something went wrong, and handle the problem accordingly.   ;  actually using c-style return codes in C++ is a real pain in larger programs because it's not particularly simple to have them propogate up the stack like exceptions. Sure you can, but then you have to do something like standardize the return codes in your program and have a huge list of constants, etc; it just gets complicated.Here's the deal with exceptions - they are slow if not used properly. Basically, ask yourself: will an exception be thrown at least once per frame? Then that's too many - you're not using them then to signal exceptional situations.What's an exceptional situation? For example, it would be if you tried to read in a file from the disk (a model, texture, etc) and it's not there. Go ahead and throw one.What's not? Say you have a SetPixel routine that performs clipping, and it throws an exception every time you plot a pixel with invalid coordinates. It's something that's probably going to happen, so it's no longer exceptional. If you really want  the feedback/error, then this is where to go back to return codes.Otherwise, I haven't seen any significant slow down from exceptions.   ;  Newbies worry too much about optimization. They should spend more time learning about better ways of doing things, instead of faster ways of doing things. Faster is not always better. Spending time on optimization is not an effective use of a newbie's time.Having said that...Exceptions have a small performance cost, just by turning on exception handling. Excessive/inefficient usage of exceptions can have a big performance cost.There are tradeoffs. While exceptions can be used effectively to solve some problems, they also increase the complexity of the code.I generally don't use them unless I have to.;Quote:Original post by JohnBoltonThere are tradeoffs. While exceptions can be used effectively to solve some problems, they also increase the complexity of the code.I generally don't use them unless I have to.They are most useful when you have a lot of operations that may fail (whatever that means to you), you don't want your program to crash and you want to avoid the combinatorial explosion of error handling control flows.I don't agree that exceptions increase code complexity, they just make complex error handling code way more compact. The same thing written without exceptions usually is just as complex but many times longer.   ;  Exceptions actually make code less complex. Exception handling is not about writing try and catch all over the place. Proper use of RAII and non-throw commit idioms allow you to remove all those trys and catches except from the code that actually knows how to handle the error.   ;  There was some discussion here and I attempted some vague tests of C++ exception performance (and also tests of a roughly equivalent C version using setjmp/longjmp). Thrown exceptions were (comparatively) very slow - still about 160K exceptions per second (on a P4 3GHz), but you really don't want to be throwing an exception for every object in your world on every frame, even if they simplify the control flow. (I think they get immensely slower if you're debugging the program in the VS IDE, because it prints a message to the Output window every time an exception is thrown. But I can't remember the precise details - try it yourself if you want a more accurate impression.)When not throwing exceptions (but with exception handling enabled anyway, since libraries like STL seem to prefer that), the 'try' blocks have very little impact - so it seems fine (in terms of performance) to use exceptions for things which really are exceptional and which will hopefully never happen. (But given the rest of that thread, it seems nobody can agree on whether you ought to use them everywhere or nowhere or for certain situations. I tend to prefer just writing code that has no failure states so there's no need to think about how to signal errors [smile])   ;Quote:Original post by jantaDo you think it's better to disable them ?Definitely not.It is my experience that those who claim they can get faster programs by turning off exceptions generally mean they can get faster programs be removing all error checking and handling.  They can write a program that does the wrong thing much faster than one that does the right thing.The cost of turning on exception handling in a modern C++ compiler (particularly MSVC and GCC, I'm less familiar with the others) is indistinguishable from zero.  There is a small cost for the use of a try-catch block, but properly written code should have very very few of those.  There is a large cost with throwing an exception, but proper use of exceptions dictate that such use should be, by deinition, exceptional.You are likely to find that if you develop your software using established exception-safe techniques, you end up with cleaner, faster, and more robust code.  Why on earth would consider the alternative, unless you are entering an obfuscated C code contest or have a manager who still lives in the 1970s?   ;  Hi, many replies I see and thanks for that. Of course I,m not planning to have my 3D object to throw an exceptino catched by the renderer as a way ton inform them they must be clipped out ;-) (just a silly example)What I had in mind was rather exeptions for file reading, network connections, database queries. And of course all at initialisation time or at least not a damn thousand times per frame (no even once if I could, to be honest)Now having read what you wrote, I wonder if there is a performance cost by just turning them on in the compiler. I mean, would it also slow down code which is not in a try/catch block ?Quote:Original post by JohnBoltonNewbies worry too much about optimization. They should spend more time learning about better ways of doing things, instead of faster ways of doing things. Faster is not always better. Spending time on optimization is not an effective use of a newbie's time.Hehe thanks for calling me a newbie ;) Since I called that myself, I wont blame you for that. But I think that using exception is not just a speed issue, it's also a design issue obviously, and so I'd like to make a decision now because I'm starting my project, and not change that decision until the end. I did appear to be concerned about speed, but who isn't. I believe that in games programming, it is not uncommon to trade reliability for speed.I mean, what if for example a reading a file fails ? If all resource files are where they should be, it should not fail. If it does, it is either because the player has changed something (too bad for him) or because of another reason that I dont have control over either (same goes for a memory allocation...) So exceptions or not, the game will have to end in a way or another. I'm not just too fan of checking everything in a game when it's just to tell the player "your game has had an error, it will not close, really sorry for that", because windows does that very well :) Of course if the situation can be helped, possible handlable errors have to be checked in a proper way (and I do do that). Hmmm just a very personnal opinion, I'm open for changing my mind of course.Thank you all for the input !Cheers, Janta;Quote:I mean, would it also slow down code which is not in a try/catch block ?Usually, yes. The compiler generates some bookkeeping code to deal with exception propagation in any function that an exception could propagate "through," even if that function doesn't have a try/catch block. This overhead is generally quite negligible (six or seven lines of assembly, if I recall correctly from the last time I was investigating the subject).Quote:So exceptions or not, the game will have to end in a way or another. I'm not just too fan of checking everything in a game when it's just to tell the player "your game has had an error, it will not close, really sorry for that", because windows does that very well :) Of course if the situation can be helped, possible handlable errors have to be checked in a proper way (and I do do that). Hmmm just a very personnal opinion, I'm open for changing my mind of course.Lies! In general, an error -- described by an exception or not -- should be handled at the lowest point it is safe and sane to do so (and recover from, if possible). A missing file is not neccessarily something that should kill your game. This is one of the mistakes people who have not really dealt with exceptions before tend to make:int main(void){  try {    RunMyGame();    }  catch(...) {    std::cerr << "Oops, an error happened! Goodbye.\n";  }  return (0);}And that constitutes the entirety of their exception "handling" and they continue on, happily assuming they have "exception safe" code, and that they are riding the cutting edge of C++ by using exceptions.Except (har har), they are very often wrong.While having a top-level catch block (probably should have one for std::exception& as well as a catch-all, incidentally), is all well and good, it's not really helping any. A robust solution to a "file-not-found" exception thrown during level load would be to replace the asset with a dummy "missing asset" object, or backing out to the main menu, or just about anything except allowing the exception to propagate all the way to main() where it will be caught causing termination of your application. You should catch and recover at the earliest sane point; in this case, the generic file-handling routines that throw the exception don't know the proper way to recover, but the less-generic asset-loading routines might ("replace with dummy asset, continue") or the less-generic level-loading code might ("bogus level data, return to main menu"). Catching at one of those points and recovering leads an application that can withstand failures in a much more user-friendly fashion, and I would argue that "should my app be more user friendly?" is a given, never a personal opinion :POf course, this is not without its pitfalls: this neccessitates having multiple catch blocks in your program. When you have only one "master" catch, you can ignore the thorny issues of making sure your code is safe in the presence of an exception because your application is dying anyway -- most resources you leak will be released for you by the OS (this is naughty, but I digress...). If you can catch and continue running, this makes writing code that properly cleans up after itself if an exception is thrown a little trickier -- this is where techniques like RAII, "scope guards" and "enforcers" come into play.This is a good read.   