Are const_iterators faster?

后端 未结 11 1880
挽巷
挽巷 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:19

    It depends on the container and implementation you use.

    Yes, const_iterator may perform better.

    For some containers the implementation of const iterators and mutable iterators may differ. A first example I can think of is the SGI's STL rope container. The mutable iterator has additional pointer to the parent rope in order to support updates. This implies additional resources wasted for reference counting updates + memory for the pointer to the parent rope. See the implementation notes here.

    However, as others said, the compiler cannot use const by itself to do optimization. const just grants read-only access to the referenced object rather than saying that it is immutable. For a container like std::vector, whose iterators are usually implemented as a simple pointers, there won't be any difference.

提交回复
热议问题