flags 對 QAbstractItemModel::match 的效能影響



秘訣: flags 只要用 Qt::MatchExactly 即可, 如果是 tree model 則再加上Qt::MatchRecursive

QModelIndexList QAbstractItemModel::match(const QModelIndex &start, int role, const QVariant &value, int hits = 1, Qt::MatchFlags flags = Qt::MatchFlags(Qt::MatchStartsWith|Qt::MatchWrap)) const


QAbstractItemModel::match中 flags 參數其實是蠻巨大的.
一般我們在輸入這個 flags 通常都是 copy / paste 舊有的 code , 所以最常看到的組合就是"Qt::MatchFixedString | Qt::MatchCaseSensitive | Qt::MatchRecursive"如以下所示,


model.match(model.index(0,0), IDRole, value, 1, Qt::MatchFixedString | Qt::MatchCaseSensitive | Qt::MatchRecursive);


這用法如果遇到value(QVariant)原本的型別是非字串, 例如int, 會導致所有比對都會先轉型成字串再作字串比對,
這是很沒有效率的, 例如對100000筆資料的list model中針對int value作match得到以下的結果,
match for int value flagselapsed (ms)
Qt::MatchFixedString | Qt::MatchCaseSensitive | Qt::MatchRecursive125593
Qt::MatchFixedString | Qt::MatchCaseSensitive120216
Qt::MatchExactly22162
由此可見型別搞錯會造成的影響有多嚴重,
還有一點就是如果是list model的話, 就不必要下Qt::MatchRecursive, 這樣又可增進一點效能.
另外對string value作match得到的結果如下,
match for string value flagselapsed (ms)
Qt::MatchFixedString | Qt::MatchCaseSensitive56188
Qt::MatchExactly55194
於此可見, 如果match要compare的value是要完全一致的, 其實只要使用Qt::MatchExactly就萬無一失了.

0 comments