QContiguousCache Class

The QContiguousCache class is a template class that provides a contiguous cache. More...

Header: #include <QContiguousCache>
qmake: QT += core
Since: Qt 4.6

This class was introduced in Qt 4.6.

Note: All functions in this class are reentrant.

Detailed Description

The QContiguousCache class provides an efficient way of caching items for display in a user interface view. Unlike QCache, it adds a restriction that elements within the cache are contiguous. This has the advantage of matching how user interface views most commonly request data, as a set of rows localized around the current scrolled position. This restriction allows the cache to consume less memory and processor cycles than QCache.

QContiguousCache operates on a fixed capacity, set with setCapacity() or passed as a parameter to the constructor. This capacity is the upper bound on memory usage by the cache itself, not including the memory allocated by the elements themselves. Note that a cache with a capacity of zero (the default) means no items will be stored: the insert(), append() and prepend() operations will effectively be no-ops. Therefore, it's important to set the capacity to a reasonable value before adding items to the cache.

The simplest way of using a contiguous cache is to use the append() and prepend().


  MyRecord record(int row) const
  {
      Q_ASSERT(row >= 0 && row < count());

      while (row > cache.lastIndex())
          cache.append(slowFetchRecord(cache.lastIndex()+1));
      while (row < cache.firstIndex())
          cache.prepend(slowFetchRecord(cache.firstIndex()-1));

      return cache.at(row);
  }

If the cache is full then the item at the opposite end of the cache from where the new item is appended or prepended will be removed.

This usage can be further optimized by using the insert() function in the case where the requested row is a long way from the currently cached items. If there is a gap between where the new item is inserted and the currently cached items then the existing cached items are first removed to retain the contiguous nature of the cache. Hence it is important to take some care then when using insert() in order to avoid unwanted clearing of the cache.

The range of valid indexes for the QContiguousCache class are from 0 to INT_MAX. Calling prepend() such that the first index would become less than 0 or append() such that the last index would become greater than INT_MAX can result in the indexes of the cache being invalid. When the cache indexes are invalid it is important to call normalizeIndexes() before calling any of containsIndex(), firstIndex(), lastIndex(), at() or operator[](). Calling these functions when the cache has invalid indexes will result in undefined behavior. The indexes can be checked by using areIndexesValid()

In most cases the indexes will not exceed 0 to INT_MAX, and normalizeIndexes() will not need to be used.

See the Contiguous Cache example.