连续高速缓存示例
连续缓存示例展示了如何使用QContiguousCache 管理超大模型的内存使用情况。在某些环境中,内存是有限的,即使在内存有限的情况下,用户仍然不喜欢应用程序使用过多的内存。使用QContiguousCache 来管理列表,而不是将整个列表加载到内存中,这样无论访问的数据集大小如何,应用程序都可以限制内存的使用量。
使用QContiguousCache 的最简单方法是在请求项目时进行缓存。当视图请求 N 行的项目时,它也可能请求 N 行附近的项目。
QVariantRandomListModel::data(constQModelIndex&index, introle)const{如果(role!= Qt::DisplayRole)returnQVariant();introw=index.row();if(row>m_rows.lastIndex()) {if(row-m_rows.lastIndex()>lookAhead) cacheRows(row-halfLookAhead, qMin(m_count,row+halfLookAhead));else while(row>m_rows.lastIndex()) m_rows.append(fetchRow(m_rows.lastIndex()+ 1)); }else if(row<m_rows.firstIndex()) {if(m_rows.firstIndex()-row>lookAhead) cacheRows(qMax(0, row - halfLookAhead), row + halfLookAhead); else while(row<m_rows.firstIndex()) m_rows.prepend(fetchRow(m_rows.firstIndex()- 1)); }returnm_rows.at(row); }voidRandomListModel::cacheRows(intfrom, intto)const{for(inti=from; i<=to;++i) m_rows.insert(i,fetchRow(i)); }
在获取行之后,该类将确定该行是否在连续缓存的当前范围内。如果使用下面的代码也同样有效。
while (row > m_rows.lastIndex()) m_rows.append(fetchWord(m_rows.lastIndex()+1); while (row < m_rows.firstIndex()) m_rows.prepend(fetchWord(m_rows.firstIndex()-1);
但是,如果直接使用滚动条,列表通常会跳行,导致上述代码会获取新旧行之间的每一行。
使用QContiguousCache::lastIndex() 和QContiguousCache::firstIndex() 可以让示例确定缓存当前缓存的是列表的哪一部分。这些值并不代表缓存自身内存中的索引,而是缓存所代表的虚拟无限数组。
通过使用QContiguousCache::append() 和QContiguousCache::prepend() ,代码可以确保当请求的行未远离当前缓存范围时,屏幕上可能还存在的项目不会丢失。QContiguousCache::insert() 可能会从缓存中删除多个项目,因为QContiguousCache 不允许有间隙。如果您的缓存需要在间隙较大的行之间快速来回跳转,请考虑使用QCache 代替。
就是这样。这是一个非常合理的缓存,对于一个非常大的列表来说内存占用极小。在这种情况下,将单词放入缓存的访问器生成的是随机信息而不是固定信息。这样,在运行示例时,您就可以看到缓存范围是如何保持本地行数的。
QString RandomListModel::fetchRow(int position) const { return QString::number(QRandomGenerator::global()->bounded(++position)); }
此外,还值得考虑在应用程序的绘制例程之外将项目预先抓取到缓存中。这可以通过单独的线程完成,或者使用QTimer 在请求的行超出当前缓存范围之前增量扩展缓存范围。
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.