QGraphicsView 框架和性能中的大量指针转换

发布于 2024-09-05 05:37:59 字数 889 浏览 1 评论 0原文

由于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光瘦了 2024-09-12 05:37:59

性能开销大部分是预付费的;这是拥有 .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 the item->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 */}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文