Keep The Best Search Matches Without Sorting Every Result
Your app searches a local catalog, scores every match, sorts the results, and displays the best twenty. The remaining results receive a very thorough ranking before being politely ignored.
For a small catalog, that is fine. When profiling shows selection taking meaningful time—or retaining all those matches costs too much memory—we can keep a shortlist as we scan. It never holds more than twenty candidates, and only those twenty need a final sort.
We will build that collector, give equal scores a predictable order, and use it in a cancellable search. The important constraint is that each document arrives once, with its final score.
Start with the simpler options
The Stack Overflow question about finding the top three dictionary values already has a perfectly reasonable accepted answer: sort, then take a prefix. Five dictionary entries do not need a performance intervention. Its other answer also points toward partial selection with Swift Algorithms.
For a finite sequence, including lazily generated matches, Swift Algorithms already provides min(count:) and max(count:). Its max(count:) returns the largest values in ascending order; reverse that result when the best should appear first. You do not need to materialize every scored match first. Consider that API before maintaining a collector yourself.
An explicit collector gives us control over its lifetime: keep the same shortlist across batches, inspect partial results when needed, and place cancellation checks in the scoring loop. Each losing candidate can be discarded immediately. The example scans an array, but the collector’s state can outlive any one batch. Keep one owner responsible for mutating it.
Soroush Khanlou’s analysis of sorting followed by a prefix explores this tradeoff and why measurements matter. Andrey Abramov’s recent search-engine article examines the same collection stage at a different scale. Our implementation uses Apple’s existing heap; it does not reproduce SereneDB’s vector-based selection algorithm or its benchmark results.
If a database or search index already owns matching and ranking, ask it for the limited result set. Our GRDB and FTS5 search article takes that route. This pattern fits data your app already has a reason to keep in memory. It does not make downloading an entire remote catalog sensible.
Give every match a complete ordering
Add Swift Collections to your target and select its HeapModule product. The downloadable test package pins version 1.7.3. The five Swift blocks below belong in one file; the package uses Swift 6.4 and targets iOS 17 and macOS 14 or later. The heap is an established package API, not an OS 27 feature.
Higher scores win. For equal scores, a smaller stable document ID wins:
import Foundation
import HeapModule
nonisolated struct RankedMatch: Comparable, Sendable {
let id: Int
let score: Int
static func < (lhs: Self, rhs: Self) -> Bool {
if lhs.score != rhs.score {
return lhs.score < rhs.score
}
return lhs.id > rhs.id
}
}
The reversed ID comparison is deliberate. Our heap’s minimum is the worst retained match: lowest score, then largest ID. Sorting these values with > produces the display order we want.
Use a persistent unique ID, not an array position or hashValue. That makes ties independent of arrival order. Integer scores also avoid floating-point NaN complicating the ordering; a floating-point version needs an explicit policy for non-finite values.
Keep only candidates that can win
nonisolated enum RankingError: Error {
case negativeLimit
}
nonisolated struct TopMatches {
let limit: Int
private var heap = Heap<RankedMatch>()
init(limit: Int) throws {
guard limit >= 0 else { throw RankingError.negativeLimit }
self.limit = limit
}
var retainedCount: Int { heap.count }
mutating func consider(_ candidate: RankedMatch) {
guard limit > 0 else { return }
if heap.count < limit {
heap.insert(candidate)
} else if let worst = heap.min, candidate > worst {
heap.replaceMin(with: candidate)
}
}
func ranked() -> [RankedMatch] {
heap.unordered.sorted(by: >)
}
}
Before the shortlist fills, every candidate gets a place. After that, a candidate must beat the worst retained value to replace it. The optional minimum check also establishes the nonempty precondition of replaceMin(with:).
For example, a three-place shortlist with scores 95, 80 and 60 rejects a new score of 55. A score of 70 replaces 60. We do not need to know which retained item is second-best until it is time to display the results.
heap.unordered is deliberately not display order. Sort the final shortlist once, rather than sorting it after every insertion.
For N candidates and a positive limit K, selection takes O(N log(K + 1)) time in the worst case, followed by O(K log(K + 1)) for the final ordering. The collector holds O(K) candidate values; if fewer than K arrive, it holds fewer. These bounds do not include the input catalog, string storage, or scoring cost.
Score once, then offer the final value
Here is a small product policy: exact title matches beat prefixes, prefixes beat substrings, and favorites get a modest boost. Prepare folded titles when the catalog changes so each keystroke does not repeat that work:
nonisolated func searchKey(_ value: String) -> String {
value.folding(
options: [.caseInsensitive, .diacriticInsensitive],
locale: Locale(identifier: "en_US_POSIX")
)
}
nonisolated struct SearchDocument: Sendable {
let id: Int
let foldedTitle: String
let isFavorite: Bool
init(id: Int, title: String, isFavorite: Bool = false) {
self.id = id
self.foldedTitle = searchKey(title)
self.isFavorite = isFavorite
}
func match(for query: String) -> RankedMatch? {
guard !query.isEmpty else { return nil }
let base: Int
if foldedTitle == query {
base = 300
} else if foldedTitle.hasPrefix(query) {
base = 200
} else if foldedTitle.contains(query) {
base = 100
} else {
return nil
}
return RankedMatch(id: id, score: base + (isFavorite ? 10 : 0))
}
}
This is a deterministic demonstration policy, not linguistic search. It does not tokenize words, correct spelling, or provide language-specific relevance. Replace the scoring policy to suit your content while preserving the collector’s contract.
Every ID must be unique in this search snapshot. The collector does not deduplicate: offering the same document twice can consume two places. Deduplicate upstream if batches overlap. Keeping a separate set of every seen ID would add O(N) storage, so it would be misleading to hide that inside an O(K) claim.
Scores must also be complete before insertion. If one batch says a document scores 100 and another later says it scores 400, those are two candidates, not an update. If a retained score decreases, an earlier rejected candidate might deserve its place—and we no longer have that candidate. Recompute from a new snapshot when favorites or other ranking inputs change. This is a shortlist for one search, not a mutable leaderboard.
Keep the scan off the caller’s actor
@concurrent
nonisolated func search(
_ documents: [SearchDocument],
query: String,
limit: Int
) async throws -> [RankedMatch] {
var matches = try TopMatches(limit: limit)
try Task.checkCancellation()
guard limit > 0 else { return [] }
let key = searchKey(query.trimmingCharacters(in: .whitespacesAndNewlines))
guard !key.isEmpty else { return [] }
for (index, document) in documents.enumerated() {
if index.isMultiple(of: 128) {
try Task.checkCancellation()
}
if let candidate = document.match(for: key) {
matches.consider(candidate)
}
}
try Task.checkCancellation()
let result = matches.ranked()
try Task.checkCancellation()
return result
}
@concurrent explicitly moves execution away from the caller’s actor while remaining in the same task. An async function alone is not a promise that CPU work leaves the main actor. The value types are explicitly nonisolated so this file also works with MainActor default isolation.
Cancellation is cooperative. The checks stop a superseded scan, but they do not interrupt a single expensive string operation or the final sort. The interval of 128 is a policy choice, not a latency guarantee. Prepare large catalogs away from the main actor too; moving only the search does not move the earlier title normalization.
A SwiftUI caller still needs to own its task and prevent obsolete results from being installed. Check cancellation before changing request tokens or UI state, then allow late successes and failures to update the screen only if they still belong to its current request. The collector itself creates no detached tasks and publishes no UI state.
Try it with a deliberately unsorted catalog:
nonisolated func exampleSearch() async throws -> [RankedMatch] {
let documents = [
SearchDocument(id: 30, title: "Café recipes"),
SearchDocument(id: 20, title: "Café"),
SearchDocument(id: 10, title: "CAFE"),
SearchDocument(id: 40, title: "A café guide", isFavorite: true)
]
return try await search(documents, query: " café ", limit: 3)
// IDs: [10, 20, 30], scores: [300, 300, 200].
}
IDs 10 and 20 tie on score. Their input order does not decide the winner. The favorite substring match scores 110, so it cannot displace a prefix match scoring 200.
Measure the search you actually ship
The download compares the collector with a straightforward reference: score all matches, sort by score descending and ID ascending, then take a prefix. Seeded permutations, tied and negative scores, integer extremes, zero/oversized limits, and repeated batches verify the same final output. A deliberate duplicate-ID case demonstrates the unsupported update behavior.
On an Apple M2 Max running macOS 27.0.1, an optimized Swift 6.4 build produced these median times over eight measured runs. Both methods searched the same seeded shuffle of 60,000 prepared documents: six repeated short titles with unique IDs, producing many score ties. Each method had one warm-up, followed by alternating execution order:
| Query / retained limit | Bounded collector | Full sort |
|---|---|---|
cafe, best 20 of 40,000 matches | 11.40 ms | 13.79 ms |
cafe, best 30,000 of 40,000 matches | 14.62 ms | 13.79 ms |
tea, best 20 of 10,000 matches | 18.61 ms | 19.11 ms |
absent, no matches | 21.78 ms | 21.71 ms |
These measurements include query normalization, matching, scoring, candidate collection, and final sorting. They exclude catalog preparation and UI rendering. Every timed result was checked against the reference. This is one synthetic host workload, not an iPhone performance promise or a comparison with Swift Algorithms.
The broad query benefits when we retain twenty results, but full sorting wins when we retain most of its matches. The no-match query still scans every title, so there is essentially no selection work to save. That is why timing only a heap of integers would tell an incomplete story.
The exact examples also passed ten correctness tests on macOS 27.0.1 and an iOS 27.0 simulator using Xcode 27.1, in both ordinary and MainActor-default isolation modes. The native build targets iOS 17; an iOS 17 runtime and physical devices were not tested. Cancellation testing covers an already-cancelled caller, not a worst-case latency bound during string matching.
Keep full sorting when it is simpler and fast enough, especially when K approaches the number of matches. A heap can reduce selection work and retained candidates; it cannot make an expensive scorer free. Measure normalization, matching, selection and result presentation separately, then measure the user-visible operation as a whole.