“for"循环与 C++ 中 Qt 的“foreach"

2021-12-26 00:00:00 performance qt for-loop foreach c++

哪个更好(或更快),C++ for 循环或 Qt 提供的 foreach 运算符?比如下面的条件

Which is better (or faster), a C++ for loop or the foreach operator provided by Qt? For example, the following condition

QList<QString> listofstrings;

哪个更好?

foreach(QString str, listofstrings)
{
    //code
}

int count = listofstrings.count();
QString str = QString();
for(int i=0;i<count;i++)
{
    str = listofstrings.at(i);
    //Code
}

推荐答案

在大多数情况下这真的无关紧要.

It really doesn't matter in most cases.

关于 StackOverflow 上关于这种方法还是那种方法更快的大量问题,掩盖了这样一个事实:在绝大多数情况下,代码大部分时间都在等待用户做某事.

The large number of questions on StackOverflow regarding whether this method or that method is faster, belie the fact that, in the vast majority of cases, code spends most of its time sitting around waiting for users to do something.

如果您真的很担心,请自行分析并根据您的发现采取行动.

If you are really concerned, profile it for yourself and act on what you find.

但我认为您很可能会发现,只有在最密集的数据处理工作中,这个问题才有意义.差异很可能只有几秒钟,即使如此,也只有在处理大量元素时才会如此.

But I think you'll most likely find that only in the most intense data-processing-heavy work does this question matter. The difference may well be only a couple of seconds and even then, only when processing huge numbers of elements.

让您的代码首先工作.然后让它快速工作(并且只有在您发现实际的性能问题时).

Get your code working first. Then get it working fast (and only if you find an actual performance issue).

在完成功能并可以正确分析之前花费的时间优化,大部分时间都是浪费时间.

Time spent optimising before you've finished the functionality and can properly profile, is mostly wasted time.

相关文章