Dexie查詢速度慢的原因主要一個優化點是復雜查詢下的count執行。
以下摘自Dexie官方文檔:https://dexie.org/docs/Collection/Collection.count()
If executed on simple queries, the native IndexedDB ObjectStore
count() method will be called (fast execution). If advanced queries
are used, the implementation has to execute a query to iterate all
items and count them manually. Examples where count() will be fastdb.[table].where(index).equals(value).count() db.[table].where(index).above(value).count() db.[table].where(index).below(value).count() db.[table].where(index).between(a,b).count() db.[table].where(index).startsWith(value).count() // The reason it is fast in above samples is that they map to basic // IDBKeyRange methods only(), lowerBound(), upperBound(), and bound().// Examples where count() will have to count manually: db.[table].where(index).equalsIgnoreCase(value).count() db.[table].where(index).startsWithIgnoreCase(value).count() db.[table].where(index).anyOf(valueArray).count() db.[table].where(index).above(value).and(filterFunction).count() db.[table].where(index1).above(value1).or(index2).below(value2).count()
官方文檔中也說明了count在復雜查詢的情況下統計速度會變慢,至于會變慢多少呢?個人做過對比在5000條數據量的情況下,進行統計大概需要花費3秒左右,而進行同樣的查詢只需要幾十毫秒。
因此在使用Dexie進行復雜查詢且需要進行分頁操作時,應該避免進行重復的count操作。其中一個解決辦法就是加入篩選條件的緩存,當緩存的條件不變時不進行count操作而直接使用之前count出來的數據。
例如:
項目中的一個例子
項目背景:electron + node + ng-zorro的一個項目。項目需要離線處理大量的數據,沒辦法加后端,只能在純前端的項目里進行數據的加載、存儲、查詢等,且這個項目還要支持數據的篩選、分頁。在這種情況下若直接使用Dexie進行count查詢總數后再進行分頁查詢就會導致每次的查詢都非常的慢。因此使用了緩存,每次在篩選的時候判斷篩選條件是否發送變化,若發生了變化則重新進行count,若沒有變化則視為進行翻頁操作,仍使用之前的count。這樣就只會在第一次用搜索條件進行查詢的時候出現卡頓,其余時間較為流暢。