tags:

views:

454

answers:

5

If I use try/catch in WindowProc override of MFC window/view classes there is a performance hit. Why is it so and what is the alternative ?

This I caught as a result of profiling. Removing the block makes the function consume much lesser time. I am using MS VS 2008.

+2  A: 

Just using try/catch should not produce a performance hit - maybe you are throwing too many exceptions? Have you profiled your code to find out where the performance hit is coming from?

1800 INFORMATION
Very good point. The performance footprint may be from something entirely different and it's better to profile prior to any analysis.
sharptooth
+1  A: 

In usage-of-try-catch-blocks-in-c Todd Gardner explains that compilers use the "table" approach or the "code" approach to implement exceptions. The "code" approach explains the performance hit.

SebastianK
I am using MS VS 2008, how do i know which approach it is using?
vikash
MSVC can use both; from your measurements it appears it's using the code one. ISTR this applies to x86-32 code.
MSalters
A: 

I'm sure you are aware that WindowProc handles a LOT of traffic. Any code outside the switch (message) loop will be executed by every message that goes through the pump.

I just made a small dialog based MFC app, where I override the WindowProc and simply count how many times it gets called. Test showed that just moving the mouse cursor over the dialog generates more than 1000 WindowProc calls per second.

Just something to think about.

p.s. I would have added this as a comment, but I don't have enough reputation score for it yet.

Rope
Yes the windowproc is called several times more than 1000. I have a try/catch for exceptions raised inside the windowproc. Just adding try/catch increases the execution time of the windowproc
vikash
A: 

In your app class, take a look at overriding CWinApp::ProcessWndProcException. This gives you a chance at uncaught MFC CExceptions (and derivatives) raised in any command or message handler.

If you need a last chance at EVERYTHING you need to look at installing your own SEH filter.

Aidan Ryan
vikash
+1  A: 

The alternative is to put the try-catch around your own code. Most of the calls to your WndProc end up in DefaultWindowProc*, which doesn't throw C++ exceptions. So, by moving the try/catch closer to your own code, you save a lot of overhead.

[*] DefaultWindowProc might throw SEH exceptions, for instance to grow the stack, but you're not supposed to handle those.

MSalters
Answer inspired by Rope's observation.
MSalters