Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are const_iterators faster?

Our coding guidelines prefer const_iterator, because they are a little faster compared to a normal iterator. It seems like the compiler optimizes the code when you use const_iterator.

Is this really correct? If yes, what really happens internally that makes const_iterator faster?.

EDIT: I wrote small test to check const_iterator vs iterator and found varying results:

For iterating 10,000 objects const_terator was taking a few milliseconds (around 16 ms) less. But not always. There were iterations in which both were equal.

like image 264
aJ. Avatar asked Apr 16 '09 09:04

aJ.


2 Answers

If nothing else, a const_iterator reads better, since it tells anyone reading the code "I'm just iterating over this container, not messing with the objects contained".

That's a great big win, never mind any performance differences.

like image 135
unwind Avatar answered Oct 07 '22 01:10

unwind


The guideline we use is:

Always prefer const over non-const

If you tend to use const object, you get used to using only constant operations on the objects you get and that is as much as using const_iterator as much as possible.

Constness has a viral property. Once you get to use it, it propagates to all your code. Your non-mutating methods become constant, and that requires using only constant operations on the attributes, and passing constant references around, that itself forces only constant operations...

To me, the performance advantage of using constant iterators over non constant iterators (if any at all) is much less important than the improvement in the code itself. Operations meant (designed) to be non-mutating are constant.

like image 41
David Rodríguez - dribeas Avatar answered Oct 07 '22 02:10

David Rodríguez - dribeas