QGraphicsView 框架和性能中的大量指针转换
由于 QGraphicsScene 和 QGraphicsItem 的大多数便利函数(例如 items()、collidingItems()、childItems() 等)返回 QList,因此您被迫执行大量 qgraphicsitem_cast 或 static_cast 和 QGraphicsItem::Type() 检查当场景中有很多不同类型的物品时,抓住实际的物品。我认为进行大量子类转换并不是理想的编码风格,但我想在这种情况下没有其他可行的方法,或者有吗?
QList<QGraphicsItem *> itemsHit = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (QGraphicsItem *item, itemsHit) {
if (item->type() == QGraphicsEllipseItem::type()) {
QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);
// do something
}
else if (item->type() == MyItemSubclass::type()) {
MyItemSubClass *myItem = qgraphicsitem_cast<MyItemSubClass *>(item);
// do something
}
// etc
}
上面的 qgraphicsitem_cast 可以用 static_cast 替换,因为已经验证了正确的类型。当一直进行大量此类操作时(非常动态的场景),大量的演员转换是否会影响正常 if-else 评估之外的性能?
Since most of the convenience functions of QGraphicsScene and QGraphicsItem (such as items(), collidingItems(), childItems() etc.) return a QList you're forced to do lots of qgraphicsitem_cast or static_cast and QGraphicsItem::Type() checks to get hold of the actual items when you have lots of different type of items in the scene. I thought doing lots of subclass casts were not a desirable coding style, but I guess in this case there are no other viable way, or is there?
QList<QGraphicsItem *> itemsHit = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (QGraphicsItem *item, itemsHit) {
if (item->type() == QGraphicsEllipseItem::type()) {
QGraphicsEllipseItem *ellipse = qgraphicsitem_cast<QGraphicsEllipseItem *>(item);
// do something
}
else if (item->type() == MyItemSubclass::type()) {
MyItemSubClass *myItem = qgraphicsitem_cast<MyItemSubClass *>(item);
// do something
}
// etc
}
The above qgraphicsitem_cast could be replaced by static_cast since correct type is already verified. When doing lots of these all the time (very dynamic scene), will the numerous casting affect performance beyond the normal if-else evaluation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
性能开销大部分是预付费的;这是拥有 .
type()
成员的开销的结果。检索一次item->type()
可能会很有效。您知道它不会改变,但编译器很可能不会改变。[编辑]
另外,如果您确实有很多类型,那么引入一些中间类型可能是值得的。例如。
if (dynamic_cast(item)) {/* 检查这些类型 */} else {/* 其他类型 */}
The performance overhead is mostly prepaid; it's the result of the overhead of having the .
type()
member. It might be efficient to retrieve theitem->type()
once. You know it doesn't change, but chances are the compiler doesn't.[edit]
Also, if you really have a lot of types, it could be worthwhile to introduce some intermediate types. eg.
if (dynamic_cast<MyGraphicsInterMediateType*>(item)) {/* check those types */} else {/* other types */}