I have a program that:
load some data from disk into std::map in memory. std::map keeps the data sorted.
save sorted data to disk
I am wondering if heap will be faster if I do this:
load some data from disk into std::vector in memory.
sort the vector
save the data to disk
or even using heap:
load some data from disk into std::vector in memory.
make a heap in the vector
pop from heap and save the data to disk
What will be fastest?
Asymptotically all of your approaches are O(n log n):
std::map is logarithmic in the size of the container. Inserting n elements will be O(n log n).std::sort on an std::vector is O(n log n).std::make_heap. However, poping an element from the heap is logarithmic in the size of the heap. Poping n elements from the heap is O(n log n).However, I expect the approaches consisting of sorting the std::vector and the heap to be faster than the one with the std::map since they take more advantage of the cache thanks to better data locality, i.e., the elements in these two cases consist of contiguously allocated blocks in memory rather than nodes spread out in memory as with the std::map.
Note also that the approach with the std::map requires more space than the other two because of the pointers that glue the map's nodes together.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With