Skip to content
Tags

Avoid early pessimizations with Qt

by razvanpetru on December 29th, 2009

Containers

First of all, know your data structures. Then, make sure you understand what kinds of optimizations the Qt containers employ under the hood. Ready? Let’s get to business then!

As you’ve probably read in the Qt Quarterly article, Qt containers (and other expensive to copy classes) use an optimization known as copy-on-write. The basic idea is that when a container is copied, the new copy shares the original container’s data instead of recreating it. Only when the data is modified does the modified container detach from the shared data and incurs the full copying cost. Assuming that you can’t avoid making copies of containers, the next best thing is to make sure that you don’t detach unless you have to.

Here are the tips:

  • Use Q_DECLARE_TYPEINFO to inform the containers whether your type can be moved in memory.
  • Use at instead of the operator[] if you need to access a container element but don’t need to change it. The former returns a const reference to the element, while the latter detaches before returning a reference to the element.
  • Use constBegin and constEnd. As an alternative, call begin/end on a const_cast<T>(container), as the const versions don’t detach.
  • Use constFind when working with hashes or maps. You’ve guessed it: find detaches.
  • Set a breakpoint inside the detach function and watch for unexpected calls.
  • Use reserve() when you know the size of the container and the container supports it.
  • Always use const T& for user data types with foreach/Q_FOREACH

Strings

Here are my recommendations for using Qt strings:

  • Do use char* when working with string literals, not everything has to be a QString. Qt understands UTF-8 and it can create QStrings from it.
  • Use QLatin1String when you have defined QT_NO_CAST_FROM_ASCII.
  • QString uses the same copy-on-write implementation as the containers. Pay attention when calling various member functions that could detach. e.g: use at() instead of operator[], constBegin() instead of begin(), etc
  • QStringRef provides fast access to substrings without creating new QString objects.
  • Qt 4.6: #include QStringBuilder to get fast concatenation with the % operator. This method avoids multiple memory allocations.

Finally, here are some performance recommendations straight from the Qt devs:

  1. Copy on write performance
  2. STL vs QTL
  3. Qt DevDays 2009 performance talk
  4. Fast container iteration
  5. Graphics performance overview
  6. Raster graphics performance
  7. OpenVG performance

From → Programming

One Comment
  1. Please post full blogs to the rss feed. It looks like it will be worth reading.

Comments are closed.