How slow is dynamic_cast?

本文通过实验对比了C++中dynamic_cast、reinterpret_cast及虚拟方法的性能。结果显示dynamic_cast比简单调用慢约20倍,但在类型检查方面更通用。

C++ users are advised frequently not to use dynamic_cast, because it's slow.

I thought it would be nice to measure this, so I made up a test on Visual C++. All you need is a simple hierarchy of types with a baseclass, a derived class, and another class derived from that.

The test is this: if you only know that an object is derived from the base class, prove whether or not it's of a certain type and (if so) call an appropriate method on it. And you typically want to be able to measure how fast you can determine that a base class is not of a certain type too.

The typical workaround to dynamic_cast is to make a base virtual method like this:

virtual int32 Name() = 0;

I measured that too.

Here's how things wind up in my test:

Base case

Use reinterpret_cast on a known type, call a simple 2-cycle method.
Result: 1.1B operations/sec (half my CPU speed, good)

Virtual case

Implement a virtual method per derived class, call it, check the result. If it matches what we want, follow the base case.
Result: 270M operations/sec for positive and negative tests

dynamic_cast case

Calls dynamic_cast, and if non-NULL result, calls a method.
Proof positive (is the type you want): 21M operations/sec
Proof negative (NULL result, single derivation): 15M operations/sec
Proof negative (NULL result, two-level derivation): 11M operations/sec

Conclusions

dynamic_cast costs a lot. A simple call can use 100-200 cycles under Visual C++. Calling a virtual function (or checking a base-class member) and testing the result can run up to 20x faster.

However, it is more general than the other listed methods (because you can cast to intermediate types), and it doesn't use extra space in your binary like a bunch of virtual functions do.

But it's not so advisable in performance-critical code.

转载于:https://www.cnblogs.com/whyandinside/archive/2010/03/08/1680728.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值