Caching the end iterator - Good idea or Bad Idea?

前端 未结 8 1831
臣服心动
臣服心动 2021-02-04 03:36

Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:



        
8条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-04 04:16

    Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes?

    If you use the STL container algorithms the caching of the end iterator is happens anyway (as you pass the result of container.end() as a parameter).

    If you modify the memory of the container (insert/remove elements) it's a bad bad idea.

    Also, caching for efficiency rarely makes much sense: in most cases the end() is inlined by the compiler, and when it is not, it is very probable that your efficiency doesn't hang on the end() result being cached. YMMV though.

提交回复
热议问题