can end()是stl容器的一个代价昂贵的操作 [英] Can end() be a costly operation for stl containers

查看:110
本文介绍了can end()是stl容器的一个代价昂贵的操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

http://doc.qt.nokia.com/qtcreator-extending/coding- style.html ,建议编写以下循环:

On http://doc.qt.nokia.com/qtcreator-extending/coding-style.html it is recommended to write for loops like the following:

Container::iterator end = large.end();
for (Container::iterator it = large.begin(); it != end; ++it) {
        //...;
}

而不是

for (Container::iterator it = large.begin(); it != large.end(); ++it) {
        //...;
}

由于我很少在任何代码中看到这种风格,我想知道是否对end()的连续调用真的对stl容器上的大循环增加了明显的运行时开销,或者编译器是否已经优化了这种情况。

Since I have rarely seen this style in any code, I would like to know whether the consecutive call of end() really adds a noticeable run-time overhead for large loops over stl containers or whether compilers already optimize such cases.

编辑:
很多非常好的评论指出:这个问题只有当循环中的代码不修改结束迭代器时才有效。

推荐答案

C ++ 11标准(第23.2.1节)强制要求 end 有O(1)复杂性,因此一个合格的实现将具有两个版本相同的性能特性。

The C++11 standard (§ 23.2.1) mandates that end has O(1) complexity, so a conforming implementation would have the same performance characteristics for both versions.

也就是说,除非编译器可以证明 end 的返回值永远不会改变,因此将 end

That said, unless the compiler can prove that the return value of end will never change then pulling end out of the loop might be faster by some constant quantity (as Steve Jessop comments, there are lots of variables that can influence whether this is true or not).

可能会更快一些常量(如Steve Jessop所说,有很多变量可以影响这是否为真) >仍然,即使在一个特定的情况下,绝对没有性能差异,拉这样的测试出循环是一个好习惯进入。 更好的习惯是使用标准算法,因为@pmr说,完全回避问题。

Still, even if in one particular case there is absolutely no performance difference, pulling such tests out of the loop is a good habit to get into. An even better habit to get into is to utilize standard algorithms as @pmr says, which sidesteps the issue entirely.

这篇关于can end()是stl容器的一个代价昂贵的操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆