Difference in performance between map and unordered_map in c++

后端 未结 3 1977
借酒劲吻你
借酒劲吻你 2020-12-30 02:07

I have a simple requirement, i need a map of type . however i need fastest theoretically possible retrieval time.

i used both map and the new proposed unordered_map

相关标签:
3条回答
  • 2020-12-30 02:46

    The extra time loading the unordered_map is due to dynamic array resizing. The resizing schedule is to double the number of cells each when the table exceeds it's load factor. So from an empty table, expect O(lg n) copies of the entire data table. You can eliminate these extra copies by sizing the hash table upfront. Specifically

    Label.reserve(expected_number_of_entries / Label.max_load_factor());
    

    Dividing by the max_load_factor is to account for the empty cells that are necessary for the hash table to operate.

    0 讨论(0)
  • 2020-12-30 02:52

    unordered_map (at least in most implementations) gives fast retrieval, but relatively poor insertion speed compared to map. A tree is generally at its best when the data is randomly ordered, and at its worst when the data is ordered (you constantly insert at one end of the tree, increasing the frequency of re-balancing).

    Given that it's ~10 million total entries, you could just allocate a large enough array, and get really fast lookups -- assuming enough physical memory that it didn't cause thrashing, but that's not a huge amount of memory by modern standards.

    Edit: yes, a vector is basically a dynamic array.

    Edit2: The code you've added some some problems. Your while (! LabelFile.eof() ) is broken. You normally want to do something like while (LabelFile >> inputdata) instead. You're also reading the data somewhat inefficiently -- what you apparently expecting is two numbers separated by a tab. That being the case, I'd write the loop something like:

    while (LabelFile >> node >> label)
        Label[node] = label;
    
    0 讨论(0)
  • 2020-12-30 03:03

    Insertion for unordered_map should be O(1) and retrieval should be roughly O(1), (its essentially a hash-table).

    Your timings as a result are way OFF, or there is something WRONG with your implementation or usage of unordered_map.

    You need to provide some more information, and possibly how you are using the container.

    As per section 6.3 of n1836 the complexities for insertion/retreival are given:

    • http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1836.pdf

    One issue you should consider is that your implementation may need to continually be rehashing the structure, as you say you have 100mil+ items. In that case when instantiating the container, if you have a rough idea about how many "unique" elements will be inserted into the container, you can pass that in as a parameter to the constructor and the container will be instantiated accordingly with a bucket-table of appropriate size.

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