2012-07-06 107 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構造是如此的微不足道,我會期待它被完全優化。