Why vector is faster than vector in the following case

后端 未结 2 765
星月不相逢
星月不相逢 2021-02-08 19:22

This phenomenon is found when I programmed for the LeetCode problem N-Queens.

I have two versions of accepted code, the only difference between which is the way I stored

相关标签:
2条回答
  • 2021-02-08 20:04

    My interpretation:

    There's a vector<type> specialization for bool, which is a bit map; that's highly efficient with regard to storage (1Byte of vector storage = 8 bool), but worse at actually accessing the data; for any other vector, you can just access the element at the nth position by *([address of first element + n * sizeof(element)]), but for the getting bool-out-of-byte storage, you'll inevitably will need to do some bit operations, which, in times of large caches, might be significantly slower than just having an array of ints, representing one truth value each.

    0 讨论(0)
  • 2021-02-08 20:24

    Access to single bits is usually slower than to complete addressable units (bytes in the lingo of C++). For example, to write a byte, you just issue a write instruction (mov on x86). To write a bit, you need to load the byte containing it, use bitwise operators to set the right bit within the byte, and then store the resulting byte.

    The compact size of a bit vector is nice for storage requirements, but it will result in a slowdown except when your data becomes large enough that caching issues play a role.

    If you want to have speed and still be more efficient than 4 bytes per value, try a vector<unsigned char>.

    0 讨论(0)
提交回复
热议问题