本文介绍了typeid()比dynamic_cast更快<>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 限时删除!! 你好, 我刚做了一个简单的基准测试: for(xx = 0; xx< 100000; xx ++){ rDerived * derived = dynamic_cast< rDerived *>(object); if(derived)derived-> setValue(message.data.messageSetInt.value); } 对: for(xx = 0; xx< 100000; xx ++){ if(typeid(object)== typeid(rDerived *))((rDerived *) object) - > setValue(message.data.messageSetInt.value); } 后一种情况将前者从水中吹走。使用带有 C样式转换的typeid()比使用dynamic_cast<>快94倍。 因此使用typeid()真的更好吗和C风格的演员而不是 (显然)更慢的dynamic_cast<>? $ * $ div $ = h2_lin >解决方案 假设你打算写''static_cast'',而不是''C style cast'',你不应该使用: 这取决于。使用dynamic_cast,您可以使用比使用typeid更广泛的实际类型来实现 ''object''。使用typeid你告诉编译器 你只对一种特定类型感兴趣,所以它可以更快, 以及更具体地表达意图代码。 顺便说一下,为什么不使用''++ xx'',为什么不在循环中声明''xx''? 如果rDerived实际上是sDerived,那么该版本是什么?b $ b正确呢? 他们做不同的事情。当你比较typeids时,你只会进行一次比较 。当你使用dynamic_cast时,你会继续寻找类型匹配的继承 层次结构。当然,后者 的好处是,如果你以各种方式改变你的继承 等级,它实际上得到了正确的答案。 使用typeid只是更好的如果你不在乎代码是多么强大 并且你已经确定类型比较是你的 应用程序的瓶颈。 - Pete Becker Dinkumware,Ltd。( http://www.dinkumware.com ) Hello,I just did a simple benchmark:for (xx=0;xx<100000;xx++) {rDerived* derived = dynamic_cast<rDerived*>(object);if (derived) derived->setValue(message.data.messageSetInt.value);}against:for (xx=0;xx<100000;xx++) {if (typeid(object) == typeid(rDerived*)) ((rDerived*)object)->setValue(message.data.messageSetInt.value);}And the latter case blew the former out of the water. Using typeid() with aC style cast was 94 times faster than using dynamic_cast<>.So is it really better to use typeid() and a C style cast rather than the(apparantly) slower dynamic_cast<>?Jamie Burns. 解决方案Assuming you meant to write ''static_cast'', not ''C style cast'', which youshould never use:It depends. With dynamic_cast you allow a wider range of actual types for''object'' than you do with typeid. With typeid you tell the compiler thatyou''re only interested in one particular type, and so it can be faster,as well as more specifically expressing the intent of the code.Btw., why not use ''++xx'', and why not declare ''xx'' in the loop?What if rDerived is actually sDerived, which version iscorrect then?They do different things. When you compare typeids you''re only makingone comparison. When you use dynamic_cast you''re walking the inheritancehierarchy looking for a type match. Of course, the benefit of the latteris that it actually gets the right answer if you change your inheritancehierarchy in various ways.Using typeid is only "better" if you don''t care how robust the code isand you''ve determined that the type comparison is a bottleneck in yourapplication.--Pete BeckerDinkumware, Ltd. (http://www.dinkumware.com) 这篇关于typeid()比dynamic_cast更快<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-08 10:45