When I want to make sure that the entry I want to use exists, I usually do this.
#include <unordered_map>
struct type { int member; };
std::unordered_map<type> map;
if (map.find(key) != map.end())
map[key].member = 42;
However, I think it performs two lookups for key
in the hash map. This caches the lookup.
#include <unordered_map>
struct type { int member; };
std::unordered_map<type> map;
auto find = map.find(key);
if (find != map.end())
find->second.member = 42;
The first option feels way more expressive. Is it really slower?
It may be slower, it may not (you're now doing an extra write in your "speed up") but one really shouldn't worry about such minor optimisations when writing code. Write clear expressive code. Then if your program really is too slow, run profiling tools on it and find your bottleneck(s). If this code is in fact a real problem, then and only then try your "speed up" and see if it matters.
Yes, because you search the key twice: map[key]
search for the key exactly like map.find
, of which you threw away the result.
It's like open a drawer to see if there is a given object, say "ah yes!" and close the drawer, then open it up again and research the object to change it.
The second code opens the drawer, search for an object and change it.
There can be compiler optimizations that allow to avoid the double search, or that may reduce the search in constant time, and there can be compiler optimization that allow to avoid the auto find
variable to be stored on memory (it can be a CPU register, since it usage is very local).
The entire problem, will in effect reduce in comparing the time for twice hash computation twice (and walk the eventual map slot, in case of hash collision) and the time to access the extra variable:
2*H < H+M
That means H < M
. If M is a register and H is not trivial, it's hard for H
to be less than M
.
Yes, it may be slower but probably not measurably slower. There is some extra work involved:
So to sum up if:
then you might see a difference.
As a final word - it probably won't matter and it's not big architectural difference but 5s optimization. So write whatever you find easier to maintain and revisit the question when the profiler will show that this functions causes a slowdown.
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