[xsd-users] Substitution groups & determining run-time type
boris at codesynthesis.com
Wed Nov 11 12:03:59 EST 2009
Durkan, Ian <ian.durkan at progeny.net> writes:
> I'm in a situation where I need to determine the type of an element at
> runtime, when the element may be any of a substitution group. I
> understand how to use dynamic_cast<T> to determine the run-time type of
> the element object, but I'm concerned about the performance of this
> method vs. accessing the DOMElement behind the object and calling its
> getTagName function and performing a string comparison. Does anyone
> have information about which approach would yield better performance?
I am pretty sure dynamic_cast is going to be faster. I made a little
test which I compiled with g++ 4.3.4 with -O3 and ran on 2.2Ghz Nahalem
Xeon (E5520). Here are the results:
virtual call : 0.0026 microseconds/call
dynamic cast : 0.0104 microseconds/call
strcmp : 0.0244 microseconds/call
So dynamic_cast (from base to derived) is about 4 times as expensive
as a virtual function call. And string comparison is about 2 times as
expensive as dynamic_cast. This is not taking into account the time
it will take to get the string from DOMElement (an additional virtual
You may also want to check Technical Report on C++ Performance,
section 5.3.8. In particular, it mentions a C++ compiler implementation
with this dynamic_cast case and a virtual function call taking the
same time. So it also depends on the compiler.
But, overall, I think the times for all three cases are negligible
on modern hardware. I had to run the test loop 100,000,000 times --
anything less was rounded to 0.
The two test files are attached. If you want to run the test, check the
assembly code first to make sure your C++ compiler didn't optimize
anything important away.
More information about the xsd-users