Why is it so slow iterating over a big std::list?

后端 未结 6 2171
生来不讨喜
生来不讨喜 2020-12-30 18:08

As title suggests, I had problems with a program of mine where I used a std::list as a stack and also to iterate over all elements of the list. The program was taking way to

6条回答
  •  独厮守ぢ
    2020-12-30 18:40

    The simple answer is because iterating over a vector isn't iterating at all, it's just starting at the base of an array and reading the elements one after another.

    I see this is marked C++, not C, but since they do the same thing under the covers it's worth pointing out that you can add elements to the beginning and end of an array by allocating it arbitrarily large, and realloc()ing and memmove()ing between 2 companion arrays if and when you run out of room. Very fast.

    The trick to adding elements to the beginning of an array is to bias the logical start of the array by advancing the pointer into the array at the start, and then backing it up when adding elements at the front. (also the way a stack is implemented)

    In exactly the same way, C can be made to support negative subscripts.

    C++ does all this for you with the vector STL class, but still worth remembering what's going on under the covers.

提交回复
热议问题