Skip to content
Myr

Use LSD radix sort for Result sorting in matcher

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Replace comparison-based pdqsort with LSD radix sort on the uint64 sort key. Radix sort is O(n) vs O(n log n) and avoids pointer-chasing cache misses in the comparison function. Sort scratch buffer is reused across iterations to reduce GC pressure. Benchmark (single-threaded, Chromium file list): - linux query (180K matches): ~16% faster - src query (high match count): ~31% faster - Rare matches: equivalent (falls back to pdqsort for n < 128)

authored by Junegunn Choi · committed by Junegunn Choi · parent 3e751c4 · Browse files · 5 files+145 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+145 added−6 removed

  • other:+145 added−6 removed

5 files+145 added−6 removed

modified:src/matcher.go+3 added-6 removed
1 unmodified line
23import (4 "fmt"5 "runtime"6 "sort"6 "sync"7 "time"89 "github.com/junegunn/fzf/src/util"
31 unmodified lines
41 eventBox *util.EventBox42 reqBox *util.EventBox43 partitions int44 slab []*util.Slab45 sortBuf [][]Result46 mergerCache map[string]MatchResult47 revision revision48}49
17 unmodified lines
67 eventBox: eventBox,68 reqBox: util.NewEventBox(),69 partitions: partitions,70 slab: make([]*util.Slab, partitions),71 sortBuf: make([][]Result, partitions),72 mergerCache: make(map[string]MatchResult),73 revision: revision}74}75
139 unmodified lines
215 for _, matches := range allMatches {216 sliceMatches = append(sliceMatches, matches...)217 }218 if m.sort && request.pattern.sortable {218 if m.tac {219 sort.Sort(ByRelevanceTac(sliceMatches))220 } else {221 sort.Sort(ByRelevance(sliceMatches))222 }219 m.sortBuf[idx] = radixSortResults(sliceMatches, m.tac, m.sortBuf[idx])220 }221 resultChan <- partialResult{idx, sliceMatches}222 }(idx, m.slab[idx], chunks)223 }
51 unmodified lines
modified:src/result_others.go+4 added
12 unmodified lines
13 }14 }15 return (irank.item.Index() <= jrank.item.Index()) != tac16}1718func sortKey(r *Result) uint64 {19 return uint64(r.points[0]) | uint64(r.points[1])<<16 | uint64(r.points[2])<<32 | uint64(r.points[3])<<4820}
modified:src/result_test.go+58 added
1package fzf23import (4 "math"5 "math/rand"6 "sort"7 "testing"89 "github.com/junegunn/fzf/src/tui"
172 unmodified lines
182 assert(10, 37, 39, tui.NewColorPair(4, 8, expected))183 assert(11, 39, 40, tui.NewColorPair(4, 8, tui.Bold))184 }185}186187func TestRadixSortResults(t *testing.T) {188 sortCriteria = []criterion{byScore, byLength}189190 rng := rand.New(rand.NewSource(42))191192 for _, n := range []int{128, 256, 500, 1000} {193 for _, tac := range []bool{false, true} {194 // Build items with random points and indices195 items := make([]*Item, n)196 for i := range items {197 items[i] = &Item{text: util.Chars{Index: int32(i)}}198 }199200 results := make([]Result, n)201 for i := range results {202 results[i] = Result{203 item: items[i],204 points: [4]uint16{205 uint16(rng.Intn(256)),206 uint16(rng.Intn(256)),207 uint16(rng.Intn(256)),208 uint16(rng.Intn(256)),209 },210 }211 }212213 // Make some duplicates to test stability214 for i := 0; i < n/4; i++ {215 j := rng.Intn(n)216 k := rng.Intn(n)217 results[j].points = results[k].points218 }219220 // Copy for reference sort221 expected := make([]Result, n)222 copy(expected, results)223 if tac {224 sort.Sort(ByRelevanceTac(expected))225 } else {226 sort.Sort(ByRelevance(expected))227 }228229 // Radix sort230 var scratch []Result231 scratch = radixSortResults(results, tac, scratch)232233 for i := range results {234 if results[i] != expected[i] {235 t.Errorf("n=%d tac=%v: mismatch at index %d: got item %d, want item %d",236 n, tac, i, results[i].item.Index(), expected[i].item.Index())237 break238 }239 }240 }241 }242}
modified:src/result_x86.go+4 added
12 unmodified lines
13 return false14 }15 return (irank.item.Index() <= jrank.item.Index()) != tac16}1718func sortKey(r *Result) uint64 {19 return *(*uint64)(unsafe.Pointer(&r.points[0]))20}
modified:src/result.go+76 added
337 unmodified lines
338339func (a ByRelevanceTac) Less(i, j int) bool {340 return compareRanks(a[i], a[j], true)341}342343// radixSortResults sorts Results by their points key using LSD radix sort.344// O(n) time complexity vs O(n log n) for comparison sort.345// The sort is stable, so equal-key items maintain original (item-index) order.346// For tac mode, runs of equal keys are reversed after sorting.347func radixSortResults(a []Result, tac bool, scratch []Result) []Result {348 n := len(a)349 if n < 128 {350 if tac {351 sort.Sort(ByRelevanceTac(a))352 } else {353 sort.Sort(ByRelevance(a))354 }355 return scratch[:0]356 }357358 if cap(scratch) < n {359 scratch = make([]Result, n)360 }361 buf := scratch[:n]362 src, dst := a, buf363 scattered := 0364365 for pass := range 8 {366 shift := uint(pass) * 8367368 var count [256]int369 for i := range src {370 count[byte(sortKey(&src[i])>>shift)]++371 }372373 // Skip if all items have the same byte value at this position374 if count[byte(sortKey(&src[0])>>shift)] == n {375 continue376 }377378 var offset [256]int379 for i := 1; i < 256; i++ {380 offset[i] = offset[i-1] + count[i-1]381 }382383 for i := range src {384 b := byte(sortKey(&src[i]) >> shift)385 dst[offset[b]] = src[i]386 offset[b]++387 }388389 src, dst = dst, src390 scattered++391 }392393 // If odd number of scatters, data is in buf, copy back to a394 if scattered%2 == 1 {395 copy(a, src)396 }397398 // Handle tac: reverse runs of equal keys so equal-key items399 // are in reverse item-index order400 if tac {401 i := 0402 for i < n {403 ki := sortKey(&a[i])404 j := i + 1405 for j < n && sortKey(&a[j]) == ki {406 j++407 }408 if j-i > 1 {409 for l, r := i, j-1; l < r; l, r = l+1, r-1 {410 a[l], a[r] = a[r], a[l]411 }412 }413 i = j414 }415 }416 return scratch417}