【问题标题】:Are comparisons between iterator and const_iterator inefficient?iterator 和 const_iterator 之间的比较效率低吗?
【发布时间】:2012-07-06 13:32:43
【问题描述】:

变体 a:

const auto end = whatever.end();
for (auto it = whatever.begin(); it != end; ++it)
{
    // ...
}

变体 b:

const auto end = whatever.cend(); // note the call to cend insteand of end here
for (auto it = whatever.begin(); it != end; ++it)
{
    // ...
}

是否有任何理由相信变体 b 的效率会低于变体 a,因为循环条件会比较两种不同类型的迭代器?这会导致it 上的隐式转换吗?

end 在 for 循环中被多次使用,因此我想把它吊出来。)

【问题讨论】:

  • @David 在我的具体情况下,它是std::string,但总的来说我很好奇。

标签: c++ performance c++11 iterator constants


【解决方案1】:

原则上,它可能效率较低,并导致非零成本的隐式转换。

在实践中,iteratorconst_iterator 可能参与继承关系(其中一个派生自另一个,或者都派生自 _iterator_base),因此不等式运算符定义在基类上,并且不需要隐式转换(相反,更多派生的迭代器被忽略)。即使没有这些,转换也可能很简单,可以内联和优化。

libstdc++ 通过在iteratorconst_iterator 之间定义operator==operator!= 以不同方式优化这些比较:http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a02037.html#l00295

libc++ 没有任何优化:http://llvm.org/svn/llvm-project/libcxx/trunk/include/__tree - 尽管 const_iterator 的构造函数来自 iterator 是如此微不足道,我希望它会被完全优化出来。

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 2014-04-08
    • 2017-05-27
    • 1970-01-01
    • 2011-02-20
    • 2016-05-26
    • 1970-01-01
    • 2016-11-10
    相关资源
    最近更新 更多