Skip to content

Commit 48db419

Browse files
authored
Prevent costly sort if the results will be ignored anyway. (#8379)
1 parent a52c7a2 commit 48db419

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
@@ -272,10 +272,12 @@ class InMemoryPackageIndex {
272272
/// it linearly into the [0.4-1.0] range, to allow better
273273
/// multiplication outcomes.
274274
packageScores.multiplyAllFromValues(_adjustedOverallScores);
275-
indexedHits = _rankWithValues(packageScores);
275+
indexedHits = _rankWithValues(packageScores,
276+
requiredLengthThreshold: query.offset);
276277
break;
277278
case SearchOrder.text:
278-
indexedHits = _rankWithValues(packageScores);
279+
indexedHits = _rankWithValues(packageScores,
280+
requiredLengthThreshold: query.offset);
279281
break;
280282
case SearchOrder.created:
281283
indexedHits = _createdOrderedHits.whereInScores(packageScores);
@@ -454,21 +456,29 @@ class InMemoryPackageIndex {
454456
return null;
455457
}
456458

457-
List<IndexedPackageHit> _rankWithValues(IndexedScore<String> score) {
459+
List<IndexedPackageHit> _rankWithValues(
460+
IndexedScore<String> score, {
461+
// if the item count is fewer than this threshold, an empty list will be returned
462+
int? requiredLengthThreshold,
463+
}) {
458464
final list = <IndexedPackageHit>[];
459465
for (var i = 0; i < score.length; i++) {
460466
final value = score.getValue(i);
461467
if (value <= 0.0) continue;
462468
list.add(IndexedPackageHit(
463469
i, PackageHit(package: score.keys[i], score: value)));
464470
}
471+
if ((requiredLengthThreshold ?? 0) > list.length) {
472+
// There is no point to sort or even keep the results, as the search query offset ignores these anyway.
473+
return [];
474+
}
465475
list.sort((a, b) {
466476
final scoreCompare = -a.hit.score!.compareTo(b.hit.score!);
467477
if (scoreCompare != 0) return scoreCompare;
468478
// if two packages got the same score, order by last updated
469479
return _compareUpdated(_documents[a.index], _documents[b.index]);
470480
});
471-
return list.toList();
481+
return list;
472482
}
473483

474484
List<IndexedPackageHit> _rankWithComparator(

0 commit comments

Comments
 (0)