Are const_iterators faster?

后端 未结 11 1877
挽巷
挽巷 2020-11-30 02:04

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

11条回答
  •  鱼传尺愫
    2020-11-30 02:38

    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.

提交回复
热议问题