Most efficient way to assign values to maps

前端 未结 6 1280
北荒
北荒 2021-02-07 19:30

Which way to assign values to a map is most efficient? Or are they all optimized to the same code (on most modern compilers)?

   // 1) Assignment using array ind         


        
6条回答
  •  攒了一身酷
    2021-02-07 20:00

    If there is no object at that key location, then:

    std::map::emplace is most efficient. insert is second (but will be extremely close). [] is least efficient.

    [], if there is no object there, trivial constructs one. It then calls operator=.

    insert does a copy constructor call on the std::pair argument.

    However, in the case of maps, map.insert( make_pair( std::move(key), std::move(value) ) ) is going to be close to map.emplace( std::move(key), std::move(value) ).

    If there is an object at the key location, then [] will call operator=, while insert/emplace will destroy the old object and create a new one. [] could easily be cheaper in this case.

    In the end, it depends on what your operator= vs copy-construct vs trivial-construct vs destructor costs are for your key and value.

    The actual work looking things up within the tree structure of the std::map will be so close to identical it isn't funny.

提交回复
热议问题