QMap::contains() VS QMap::find()

nbilal picture nbilal · Nov 13, 2013 · Viewed 14.9k times · Source

I often see code like:

if(myQMap.contains("my key")){
    myValue = myQMap["my key"];
}

which theoretically performs two look-up's in the QMap.

My first reaction is that it should be replaced by the following, which performs one lookup only and should be two times faster:

auto it = myQMap.find("my key");
if(it != myQMap.end()){
    myValue = it.value();
}

I am wondering if QMap does this optimization automatically for me? In other words, I am wondering if QMap saves the position of the last element found with QMap::contains() and checks it first before performing the next lookup?

Answer

TheDarkKnight picture TheDarkKnight · Nov 14, 2013

I would expect that QMap provides both functions for a better interface to the class. It's more natural to ask if the map 'contains' a value with a specified key than it is to call the 'find' function.

As the code shows, both find and contains call the following internal function: -

Node *n = d->findNode(akey);

So if you're going to use the returned iterator, then using find and checking the return value will be more efficient, but if you just want to know if the value exists in the map, calling contains is better for readability.

If you look at the source code, you'll see that QMap is implemented as a binary tree structure of nodes. Calling findNode iterates through the nodes and does not cache the result.