Skip to content

Commit b6cd555

Browse files
committed
Prevent costly sort if the results will be ignored anyway.
1 parent ec19ac0 commit b6cd555

File tree

1 file changed

+14
-4
lines changed

1 file changed

+14
-4
lines changed

app/lib/search/mem_index.dart

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -213,10 +213,12 @@ class InMemoryPackageIndex {
213213
/// it linearly into the [0.4-1.0] range, to allow better
214214
/// multiplication outcomes.
215215
packageScores.multiplyAllFromValues(_adjustedOverallScores);
216-
indexedHits = _rankWithValues(packageScores);
216+
indexedHits = _rankWithValues(packageScores,
217+
requiredLengthThreshold: query.offset);
217218
break;
218219
case SearchOrder.text:
219-
indexedHits = _rankWithValues(packageScores);
220+
indexedHits = _rankWithValues(packageScores,
221+
requiredLengthThreshold: query.offset);
220222
break;
221223
case SearchOrder.created:
222224
indexedHits = _createdOrderedHits.whereInScores(packageScores);
@@ -395,21 +397,29 @@ class InMemoryPackageIndex {
395397
return null;
396398
}
397399

398-
List<IndexedPackageHit> _rankWithValues(IndexedScore<String> score) {
400+
List<IndexedPackageHit> _rankWithValues(
401+
IndexedScore<String> score, {
402+
// if the item count is fewer than this threshold, an empty list will be returned
403+
int? requiredLengthThreshold,
404+
}) {
399405
final list = <IndexedPackageHit>[];
400406
for (var i = 0; i < score.length; i++) {
401407
final value = score.getValue(i);
402408
if (value <= 0.0) continue;
403409
list.add(IndexedPackageHit(
404410
i, PackageHit(package: score.keys[i], score: value)));
405411
}
412+
if ((requiredLengthThreshold ?? 0) > list.length) {
413+
// There is no point to sort or even keep the results, as the search query offset ignores these anyway.
414+
return [];
415+
}
406416
list.sort((a, b) {
407417
final scoreCompare = -a.hit.score!.compareTo(b.hit.score!);
408418
if (scoreCompare != 0) return scoreCompare;
409419
// if two packages got the same score, order by last updated
410420
return _compareUpdated(_documents[a.index], _documents[b.index]);
411421
});
412-
return list.toList();
422+
return list;
413423
}
414424

415425
List<IndexedPackageHit> _rankWithComparator(

0 commit comments

Comments
 (0)