c++ - std::string as map key and efficiency of map.find() -
i have std::map<std::string,foo>
, need find()
elements when instead of std::string
, have const char*
. however, map.find("key_value")
won't work, need std::string
. so, need map.find(std::string{"key_value"})
, create temporary std::string
(with allocation , de-allocation) each time, making potentially inefficient. reasoning correct? if yes, how can improve situation?
i think using wrapper around const char*
key map has own comparison function , can cheaply wrapped around const char*
, no need allocations. idea? (note mapped values not copyable, movable).
you can avoid temporaries using 0-terminated strings , custom comparator map.
still, using unordered_map
yield better indexing performance.
an alternative (much better), using wrapper, think.
there std::reference_wrapper
task.
still, first rule of optimisation: not it.
second rule: not it.
third rule (only experts): after measurement , careful consideration, might anyway.
the downside is: must manually manage lifetimes of strings.
if going down road anyway, , not free string until free them all, consider using own custom allocator.
Comments
Post a Comment