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

#39;for#39; loop vs Qt#39;s #39;foreach#39; in C++(“for循环与 C++ 中 Qt 的“foreach)

本文介绍了“for"循环与 C++ 中 Qt 的“foreach"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哪个更好(或更快),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.

这篇关于“for"循环与 C++ 中 Qt 的“foreach"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:“for"循环与 C++ 中 Qt 的“foreach"

基础教程推荐