std::string as map key and efficiency of map.find()

可紊 提交于 2019-12-25 01:48:52

问题


I have a std::map<std::string,foo> and need to frequently find() elements when instead of a std::string, I have a const char*. However, map.find("key_value") won't work, I need a std::string. So, I would need to map.find(std::string{"key_value"}), but this will create a temporary std::string (with its allocation and de-allocation) each time, making this potentially inefficient. Is this reasoning correct? If yes, how can I improve the situation?

I was think about using a wrapper around const char* as key for the map which has its own comparison function and can be cheaply wrapped around any const char*, no need for allocations. Is this a good idea? (note that my mapped values are not copyable, only movable).


回答1:


You can avoid the temporaries by using 0-terminated strings and a custom comparator for the map.
Still, using an unordered_map would likely yield better indexing performance.

An alternative (much better), is using a wrapper, just as you think.
There is actually already std::reference_wrapper for that task.

Still, the first rule of optimisation: Do not do it.
The second rule: Do not do it.
The third rule (only for experts): After measurement and careful consideration, you might do it anyway.

The only downside is: You must manually manage the lifetimes of your strings.

If you are going down that road anyway, and you do not free any string until you free them all, consider using your own custom allocator.



来源:https://stackoverflow.com/questions/23282609/stdstring-as-map-key-and-efficiency-of-map-find

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!