Skip to content

Commit 5bd0804

Browse files
committed
perf(mobile): optimize date loading with batch loading
Introduce DateBatchLoader to reduce the number of database queries by loading dates in batches, improving performance when querying large lists.
1 parent 5b63b9f commit 5bd0804

File tree

1 file changed

+54
-1
lines changed

1 file changed

+54
-1
lines changed

mobile/lib/widgets/asset_grid/asset_grid_data_structure.dart

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,20 @@ class RenderList {
147147

148148
if (groupBy == GroupAssetsBy.none) {
149149
final int total = assets?.length ?? query!.countSync();
150+
151+
final dateLoader = query != null
152+
? DateBatchLoader(
153+
query: query,
154+
totalCount: total,
155+
batchSize: 1000 * sectionSize,
156+
)
157+
: null;
158+
150159
for (int i = 0; i < total; i += sectionSize) {
151160
final date = assets != null
152161
? assets[i].fileCreatedAt
153-
: await query!.offset(i).fileCreatedAtProperty().findFirst();
162+
: await dateLoader?.getDate(i);
163+
154164
final int count = i + sectionSize > total ? total - i : sectionSize;
155165
if (date == null) break;
156166
elements.add(
@@ -320,3 +330,46 @@ class RenderList {
320330
_bufOffset = 0;
321331
}
322332
}
333+
334+
class DateBatchLoader {
335+
final QueryBuilder<Asset, Asset, QAfterSortBy> query;
336+
final int totalCount;
337+
final int batchSize;
338+
339+
List<DateTime> _buffer = [];
340+
int _bufferStart = 0;
341+
342+
DateBatchLoader({
343+
required this.query,
344+
required this.totalCount,
345+
required this.batchSize,
346+
});
347+
348+
Future<DateTime?> getDate(int index) async {
349+
if (!_isIndexInBuffer(index)) {
350+
await _loadBatch(index);
351+
}
352+
353+
if (_isIndexInBuffer(index)) {
354+
return _buffer[index - _bufferStart];
355+
}
356+
357+
return null;
358+
}
359+
360+
Future<void> _loadBatch(int targetIndex) async {
361+
final batchStart = (targetIndex ~/ batchSize) * batchSize;
362+
363+
_buffer = await query!
364+
.offset(batchStart)
365+
.limit(batchSize)
366+
.fileCreatedAtProperty()
367+
.findAll();
368+
369+
_bufferStart = batchStart;
370+
}
371+
372+
bool _isIndexInBuffer(int index) {
373+
return index >= _bufferStart && index < _bufferStart + _buffer.length;
374+
}
375+
}

0 commit comments

Comments
 (0)