Home > Software design >  constexpr array vs deque, memory utilization
constexpr array vs deque, memory utilization

Time:11-17

I need to store a pre-known size of about 30 integers in my code, I have gone for

constexpr std::array<size_t, 30> MAPPING{1, 2, 3, ...};

If i am not wrong, the above will be evaluated at compile time, but it would also take up a single sequential block of memory of a size of 30 integers?

If it does, is it worth using a std::deque instead

const std::deque<int> MAPPING{1, 2, 3, ...};

This way, with a deque, we would not be using a single large sequential memory block and it might use a bunch of fragmented blocks instead and thus it will work fine even if the memory is fragmented?

Please let me know if I have missed anything, thanks

CodePudding user response:

It's not worth using std::deque here.

It would also take up a single sequential block of memory of a size of 30 integers?


Yes, it would take up a single sequential block of memory of a size of 30 integers in the stack

This way, with a deque, we would not be using a single large sequential memory block and it might use a bunch of fragmented blocks instead and thus it will work fine even if the memory is fragmented?


It's implementation-dependent, for 30 integers they may be split into several small blocks or may not, but it will use heap memory and thus has runtime overhead:

As opposed to std::vector, the elements of a deque are not stored contiguously: typical implementations use a sequence of individually allocated fixed-size arrays, with additional bookkeeping, which means indexed access to deque must perform two pointers dereferences, compared to vector's indexed access which performs only one.

According to @Homer512's comment, we also need to notice the memory fragmentation when using the heap, there may be memory waste and we can't avoid it.

  • Related