2012-07-06 106 views
11

方案A:迭代器和const_iterator之间的比较效率低下吗?

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会比变体的效率较低,因为循环条件比较了两种不同类型的迭代器?这是否会导致it上的隐式转换?

end多次使用内部的for循环中,因此,我希望葫芦出来。)

+0

什么容器? – 2012-07-06 13:53:08

+0

@David在我的具体情况下,它是一个'std :: string',但我一般都很好奇。 – fredoverflow 2012-07-06 13:54:40

回答

12

在原理上,这可能是效率较低,导致与非零成本的隐式转换。

在实践中,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_iteratoriterator构造是如此的微不足道,我会期待它被完全优化。