C ++迭代器&循环优化 [英] C++ iterators & loop optimization

查看:230
本文介绍了C ++迭代器&循环优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到很多类似这样的c ++代码:

  for(const_iterator it = list.begin 
const_iterator ite = list.end();
it!= ite; ++ it)

与更简洁的版本相反:

  for(const_iterator it = list.begin(); 
it!= list.end(); ++ it)

速度之间这两个约定? Naive的第一个会稍快一些,因为list.end()只被调用一次。但是由于迭代器是const,看起来编译器会把这个测试从循环中拉出,为两者产生等价的装配。

解决方案

p>我只是提到的记录,C ++标准要求调用 begin() end()任何容器类型(是向量列表 map 等)必须只有固定时间。在实践中,如果您在开启优化的情况下编译,这些调用几乎肯定会内联到单个指针比较。



请注意,此保证不一定适用于其他供应商 - (例如单链表 slist )中提供的容器,这些容器实际上并不遵守作为标准的第23章中规定的容器的形式要求。 p>

I see a lot of c++ code that looks like this:

for( const_iterator it = list.begin(),
     const_iterator ite = list.end();
     it != ite; ++it)

As opposed to the more concise version:

for( const_iterator it = list.begin();
     it != list.end(); ++it)

Will there be any difference in speed between these two conventions? Naively the first will be slightly faster since list.end() is only called once. But since the iterator is const, it seems like the compiler will pull this test out of the loop, generating equivalent assembly for both.

解决方案

I'll just mention for the record that the C++ standard mandates that calling begin() and end() on any container type (be it vector, list, map etc.) must take only constant time. In practice, these calls will almost certainly be inlined to a single pointer comparison if you compile with optimisations turned on.

Note that this guarantee does not necessarily hold for additional vendor-supplied "containers" that do not actually obey the formal requirements of being a container laid out in the chapter 23 of the standard (e.g. the singly-linked list slist).

这篇关于C ++迭代器&循环优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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