Summary
I show how static event handlers through template function specializations can be simpler and more efficient than dynamic event handlers through function pointers.
Advertisement
Often in event driven frameworks, functions pointers are used, to allow the user of a library to respond to particular events generated by a library. If we know the event handlers to be static (i.e. not changing during program execution) then we can use another simpler and more efficient technique based on template function specializations.
This post is intended to replace the somewhat inelegant previous post I made. on the technique.
On my system (Windows XP) and compiler (Visual C++ 7.1) I got results of roughly 2000 msec for dynamic dispatch versus 1500 msec for static dispatch. This is not surprising considering that the compiler can much more easily optimize the template calls. Compilers are not good at guessing when dynamic contexts are in fact static. This is what programmers are for.
Notice that the static dispatch system requires far less code and does not need any kind of registration step.
I cannot argue that the template driven method looks cleaner, but the speed proof is broken in several ways. First, using only one sample as a basis for comparison as opposed to running through a loop with interrupts disabled is questionable. Second, the speed results themselves fail the sanity check, even though the proper ratio between scores is maintained. You should -divide- the clock delta by CLOCKS_PER_SEC and -multiply- by 1000 (ms/s) to have the units balance to milisecond delta. Right now it is clocks squared per 1000 milliseconds, and 1.5 to 2 seconds delay is simply unbelievable. I would like to see a fixed proof, since this is really a very good and interesting premise.
Whoops. Actually looking at the code, there is a substantial loop occuring in the handler, so I'm full of it. I just looked at main and the results and (not knowing even the order of magnitude of CLOCKS_PER_SEC) assumed the test itself was broken. My apologies!