refactor(search): replace O(n²) indexOf with HashMap for rank ordering

ids.indexOf() scans the full list for each document, giving O(n²) total.
Build a Map<UUID, Integer> once at O(n) and use getOrDefault at O(1) per
document. Behavior is identical; existing tests remain green.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Marcel
2026-04-15 10:59:05 +02:00
parent 947d8aeb6c
commit 43595aeb8a

View File

@@ -323,12 +323,11 @@ public class DocumentService {
boolean useRankOrder = hasText && (sort == null || sort == DocumentSort.RELEVANCE);
if (useRankOrder) {
List<Document> results = documentRepository.findAll(spec);
final List<UUID> ids = rankedIds;
Map<UUID, Integer> rankMap = new HashMap<>();
for (int i = 0; i < rankedIds.size(); i++) rankMap.put(rankedIds.get(i), i);
return results.stream()
.sorted(Comparator.comparingInt(doc -> {
int idx = ids.indexOf(doc.getId());
return idx < 0 ? Integer.MAX_VALUE : idx;
}))
.sorted(Comparator.comparingInt(
doc -> rankMap.getOrDefault(doc.getId(), Integer.MAX_VALUE)))
.toList();
}