c++ - 关于foreach循环和性能的几个问题

标签 c++ qt4

下面我有几个与foreach相关的问题,希望有人能回答。我知道大多数人并不关心可能微不足道的差异,但我想了解它们的完整性。

1) 有人可以解释一下 Qt 中的 foreach 关键字实际上是如何在幕后工作的吗?我想知道 foreach 是否创建一个新的项目对象指针并在下面的示例中的每次迭代中重新评估 collidingItems(可能很昂贵)

foreach (QGraphicsItem *item, someItem->collidingItems(Qt::IntersectsItemShape) {
    // do something with item;
}

因此应该这样输入

QGraphicsItem *item;
QList<QGraphicsItem *> itemList = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (item, itemList) {
    // do something with item;
 }

我假设不是,因为根据文档,它在进入循环之前获取列表的拷贝。但是,如果我没记错的话,至少有一个 for 语句会评估每次迭代的检查,所以我只想确定一下。

2) 第二个问题。由于 foreach 复制了列表,是否可以更改 foreach 中的原始内容,如

QList<QGraphicsItem *> itemList = someItem->collidingItems(Qt::IntersectsItemShape);
foreach (QGraphicsItem *item, itemList) {
    if (item->type() != QGraphicsItem::UserType)
        itemList.removeOne(item);
}
// continue using itemList

3) 最后一个问题。预先创建和重用指针(如下所示)或每次在 foreach 循环内定义一个新指针(假设一个大列表)在性能上有什么不同吗?

MyGraphicsItem *myItem;   // a complex subclass of QGraphicsItem
foreach (QGraphicsItem *item, someItem->collidingItems(Qt::IntersectsItemShape)) {
    myItem = qgraphicsitem_cast<MyGraphicsItem *>(myItem);
    // do something with myItem;
}

谢谢!

最佳答案

  1. 它确实复制了您作为 foreach 的第二个参数传递的列表。在您的例子中,collidingItems 返回的列表将被复制到 foreach 中使用的变量中。
  2. 是的,没关系(见下文)。
  3. 我认为不会有性能差异,因为指针是原始类型。如果它是类类型,并且在循环内声明它,则每次迭代都必须调用其构造函数。

来自文档:

Qt automatically takes a copy of the container when it enters a foreach loop. If you modify the container as you are iterating, that won't affect the loop. (If you don't modify the container, the copy still takes place, but thanks to implicit sharing copying a container is very fast.)

关于c++ - 关于foreach循环和性能的几个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3005408/

相关文章:

c++ - 变量具有初始值设定项但类型不完整 C++

C++ 全局函数

c++ - 仅使用宏在 header 中定义静态变量

c++ - 我的 QTreeWidgetIcons 在哪里?

qt4 - 使用 MinGW GCC 4.8.1 的 QT 4.8.5 编译问题

python - 无法在 opencv 中从 C++ 打开视频。它适用于python

android - QAndroidJniObject::callMethod() 和 QAndroidJniObject::callObjectMethod() 有什么区别?

c++ - 在几个 QMainWindows 之间共享 QUndoStack?

qt - 在 Ubuntu 10.04 Lucid Lynx 中运行 Qt 4.7 应用程序

c++ - 如何强制 QLocale::system 改变