Skip to content

Simple Qt container optimization you should do on your code

Wednesday, 13 May 2015  |  sergio.martins

Most of us know we shouldn't let our containers detach. QList, QVector, QString, etc. are implicitly shared. Copying them is cheap, but when we call a non const member function it will detach and trigger a deep copy.

This is common knowledge, but we still forget and do: Item item = fetchJob->items().first(); instead of: Item item = fetchJob->items().at(0);

Last weekend I started looking into "proper tooling" to help detect cases where we're detaching but was quickly sidetracked by "rudimentary tooling", which kept me busy fixing 50 detaches in kdepim, some of them quite expensive.

So, just run grep -R )\.first() in your source directory. Chances are you'll find lines where you're detaching from temporary containers and it's very easy to fix.

Beware of false positives: if the container isn't shared it wouldn't detach. For example, QMap::keys() returns a fresh QList created on the fly with refcount = 1. In doubt use the source.

Expect a new blog post with proper tooling soon.

UPDATE: peppe is working on adding rvalue overloads so that it never detaches when calling first()|last() on temporaries (https://codereview.qt-project.org/#/c/112343/)