Hi all,

Has anyone *benchmarked* the difference between a dynamic_cast and a virtual 
call to identify the type of a class? Before my benchmark, I guessed the 
virtual call was cheaper, but how much? I just knew it depends a lot on how 
types are related for the dynamic_cast.

Example:
    if (dynamic_cast<Target*>(pointer)) {...}
compared to:
    if (pointer->className() == "TartgetName") {...}

Well, I had these results:

Test 1: Testing if a Node is a MatrixTransform (test is true here)
dynamic_cast: 766 ticks in debug / 469 in release
className(): 265 ticks (-65%) / 31 (-94%)

Test 2: Testing if a Node is a Group (test is true here)
dynamic_cast: 512 ticks / 266
className(): 140 ticks (-72%) / 31 (-88%)

Test 3:
Testing if a Node is a Node(!) (test is true!!!)
dynamic_cast: 16 ticks / 0 (Optimized!)
className(): 140 ticks (+775%) / 31 (N/A)

Test 4:
Testing if a Node is a string (unrelated types: test is false here)
dynamic_cast: 1125 ticks / 797
className(): 110 ticks (-90%) / 31 (-96%)

Conclusions:
- For my config (see below), benchmark says that using a virtual call if *FAR* 
cheaper (roughly 10-20 times!).
- The virtual call test uses a string comparison that is of course affected by 
the length of the string, but that's even not noticeable in release.

Of course this is only a benchmark and things like CPU cache, compiler and 
options may affect results.
Anyway I didn't know the difference was so huge.

Any comments about your experience or about these tests?
Hope it helps.


***

Test config:
WinXP SP3
VC8 SP1
OSG 2.7.6

Source code for test 1:
osg::Node * p = new osg::MatrixTransform;
assert(strcmp(p->className(), "MatrixTransform")==0);
clock_t start = ::clock();
for(int i=0; i<10000000; ++i) {
        if (dynamic_cast<osg::MatrixTransform*>(p)) {
                int i=0;
        }
}
std::cout << ::clock()-start << std::endl;
start = ::clock();
for(int i=0; i<10000000; ++i) {
        if (strcmp(p->className(), "MatrixTransform")==0) {
                int i=0;
        }
}
std::cout << ::clock()-start << std::endl;


Sukender
PVLE - Lightweight cross-platform game engine - http://pvle.sourceforge.net/
_______________________________________________
osg-users mailing list
[email protected]
http://lists.openscenegraph.org/listinfo.cgi/osg-users-openscenegraph.org

Reply via email to