C++ Map Operator[] Creates Ghost Entries, Slowing Lookups From 3ms to 0ms
A developer discovered that using the square bracket operator on a C++ unordered_map to check for key existence was silently inserting default-value entries on every failed lookup. This happened because C++ operator[] allocates a new heap node and inserts a zero-value entry when a missing key is accessed, polluting the map with junk data. The accumulated ghost entries caused CPU cache thrashing and triggered costly hash table rehashes during iteration. Switching to mp.find(), a strictly read-only operation that returns mp.end() on a miss without any allocation, dropped runtime from 3ms to 0ms. Developers are advised to use find() or, in C++20, mp.contains() when checking for key presence rather than relying on the bracket operator.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in