Can I have polymorphic containers with value semantics in C++?

后端 未结 9 1463
半阙折子戏
半阙折子戏 2020-12-02 18:35

As a general rule, I prefer using value rather than pointer semantics in C++ (ie using vector instead of vector). Usuall

9条回答
  •  感情败类
    2020-12-02 19:18

    I just wanted to point out that vector is usually more efficient than vector. In a vector, all the Foos will be adjacent to each other in memory. Assuming a cold TLB and cache, the first read will add the page to the TLB and pull a chunk of the vector into the L# caches; subsequent reads will use the warm cache and loaded TLB, with occasional cache misses and less frequent TLB faults.

    Contrast this with a vector: As you fill the vector, you obtain Foo*'s from your memory allocator. Assuming your allocator is not extremely smart, (tcmalloc?) or you fill the vector slowly over time, the location of each Foo is likely to be far apart from the other Foos: maybe just by hundreds of bytes, maybe megabytes apart.

    In the worst case, as you scan through a vector and dereferencing each pointer you will incur a TLB fault and cache miss -- this will end up being a lot slower than if you had a vector. (Well, in the really worst case, each Foo has been paged out to disk, and every read incurs a disk seek() and read() to move the page back into RAM.)

    So, keep on using vector whenever appropriate. :-)

提交回复
热议问题