Improve search performance by limiting the search scope
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Find the last occurrence of the last character in the pattern and perform the search algorithm only up to that point. The effectiveness of this mechanism depends a lot on the shape of the input and the pattern.
authored by Junegunn Choi · committed by Junegunn Choi · parent a5447b8 · Browse files · 4 files·+99 added−34 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+99 added−34 removed
- other:+99 added−34 removed
Provenance
- Commit
e86b81b- Tree
f062615- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
a5447b8
4 files changed+99 added−34 removed
modified:src/algo/algo.go+51 added-31 removed
350 unmodified lines351 }352 return true353 }354 355-func asciiFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) int {355+func asciiFuzzyIndex(input *util.Chars, pattern []rune, caseSensitive bool) (int, int) {356 // Can't determine357 if !input.IsBytes() {358- return 0358+ return 0, input.Length()359 }360 361 // Not possible362 if !isAscii(pattern) {363- return -1363+ return -1, -1364 }365 366- firstIdx, idx := 0, 0366+ firstIdx, idx, lastIdx := 0, 0, 0367+ var b byte368 for pidx := 0; pidx < len(pattern); pidx++ {369+ b = byte(pattern[pidx])368- idx = trySkip(input, caseSensitive, byte(pattern[pidx]), idx)370+ idx = trySkip(input, caseSensitive, b, idx)371 if idx < 0 {370- return -1372+ return -1, -1373 }374 if pidx == 0 && idx > 0 {375 // Step back to find the right bonus point376 firstIdx = idx - 1377 }378+ lastIdx = idx379 idx++380 }381+382+ // Find the last appearance of the last character of the pattern to limit the search scope383+ bu := b384+ if !caseSensitive && b >= 'a' && b <= 'z' {385+ bu = b - 32386+ }387+ scope := input.Bytes()[lastIdx:]388+ for offset := len(scope) - 1; offset > 0; offset-- {389+ if scope[offset] == b || scope[offset] == bu {390+ return firstIdx, lastIdx + offset + 1391+ }392+ }378- return firstIdx393+ return firstIdx, lastIdx + 1394 }395 396 func debugV2(T []rune, pattern []rune, F []int32, lastIdx int, H []int16, C []int16) {397 width := lastIdx - int(F[0]) + 140 unmodified lines438 if M == 0 {439 return Result{0, 0, 0}, posArray(withPos, M)440 }441 N := input.Length()442+ if M > N {443+ return Result{-1, -1, 0}, nil444+ }445 446 // Since O(nm) algorithm can be prohibitively expensive for large input,447 // we fall back to the greedy algorithm.448 if slab != nil && N*M > cap(slab.I16) {449 return FuzzyMatchV1(caseSensitive, normalize, forward, input, pattern, withPos, slab)450 }451 452 // Phase 1. Optimized search for ASCII string435- idx := asciiFuzzyIndex(input, pattern, caseSensitive)436- if idx < 0 {453+ minIdx, maxIdx := asciiFuzzyIndex(input, pattern, caseSensitive)454+ if minIdx < 0 {455 return Result{-1, -1, 0}, nil456 }457+ // fmt.Println(N, maxIdx, idx, maxIdx-idx, input.ToString())458+ N = maxIdx - minIdx459 460 // Reuse pre-allocated integer slice to avoid unnecessary sweeping of garbages461 offset16 := 0462 offset32 := 04 unmodified lines467 // The first occurrence of each character in the pattern468 offset32, F := alloc32(offset32, slab, M)469 // Rune array470 _, T := alloc32(offset32, slab, N)451- input.CopyRunes(T)471+ input.CopyRunes(T, minIdx)472 473 // Phase 2. Calculate bonus for each point474 maxScore, maxScorePos := int16(0), 0475 pidx, lastIdx := 0, 0476 pchar0, pchar, prevH0, prevClass, inGap := pattern[0], pattern[0], int16(0), initialCharClass, false457- Tsub := T[idx:]458- H0sub, C0sub, Bsub := H0[idx:][:len(Tsub)], C0[idx:][:len(Tsub)], B[idx:][:len(Tsub)]459- for off, char := range Tsub {477+ for off, char := range T {478 var class charClass479 if char <= unicode.MaxASCII {480 class = asciiCharClasses[char]481 if !caseSensitive && class == charUpper {482 char += 32465- Tsub[off] = char483+ T[off] = char484 }485 } else {486 class = charClassOfNonAscii(char)487 if !caseSensitive && class == charUpper {1 unmodified line489 }490 if normalize {491 char = normalizeRune(char)492 }475- Tsub[off] = char493+ T[off] = char494 }495 496 bonus := bonusMatrix[prevClass][class]479- Bsub[off] = bonus497+ B[off] = bonus498 prevClass = class499 500 if char == pchar {501 if pidx < M {484- F[pidx] = int32(idx + off)502+ F[pidx] = int32(off)503 pidx++504 pchar = pattern[util.Min(pidx, M-1)]505 }488- lastIdx = idx + off506+ lastIdx = off507 }508 509 if char == pchar0 {510 score := scoreMatch + bonus*bonusFirstCharMultiplier493- H0sub[off] = score494- C0sub[off] = 1511+ H0[off] = score512+ C0[off] = 1513 if M == 1 && (forward && score > maxScore || !forward && score >= maxScore) {496- maxScore, maxScorePos = score, idx+off514+ maxScore, maxScorePos = score, off515 if forward && bonus >= bonusBoundary {516 break517 }518 }519 inGap = false520 } else {521 if inGap {504- H0sub[off] = util.Max16(prevH0+scoreGapExtension, 0)522+ H0[off] = util.Max16(prevH0+scoreGapExtension, 0)523 } else {506- H0sub[off] = util.Max16(prevH0+scoreGapStart, 0)524+ H0[off] = util.Max16(prevH0+scoreGapStart, 0)525 }508- C0sub[off] = 0526+ C0[off] = 0527 inGap = true528 }511- prevH0 = H0sub[off]529+ prevH0 = H0[off]530 }531 if pidx != M {532 return Result{-1, -1, 0}, nil533 }534 if M == 1 {517- result := Result{maxScorePos, maxScorePos + 1, int(maxScore)}535+ result := Result{minIdx + maxScorePos, minIdx + maxScorePos + 1, int(maxScore)}536 if !withPos {537 return result, nil538 }521- pos := []int{maxScorePos}539+ pos := []int{minIdx + maxScorePos}540 return result, &pos541 }542 543 // Phase 3. Fill in score matrix (H)88 unmodified lines632 s2 = H[I+j0-1]633 }634 635 if s > s1 && (s > s2 || s == s2 && preferMatch) {618- *pos = append(*pos, j)636+ *pos = append(*pos, j+minIdx)637 if i == 0 {638 break639 }640 i--4 unmodified lines645 }646 // Start offset we return here is only relevant when begin tiebreak is used.647 // However finding the accurate offset requires backtracking, and we don't648 // want to pay extra cost for the option that has lost its importance.631- return Result{j, maxScorePos + 1, int(maxScore)}, pos649+ return Result{minIdx + j, minIdx + maxScorePos + 1, int(maxScore)}, pos650 }651 652 // Implement the same sorting criteria as V2653 func calculateScore(caseSensitive bool, normalize bool, text *util.Chars, pattern []rune, sidx int, eidx int, withPos bool) (int, *[]int) {59 unmodified lines713 func FuzzyMatchV1(caseSensitive bool, normalize bool, forward bool, text *util.Chars, pattern []rune, withPos bool, slab *util.Slab) (Result, *[]int) {714 if len(pattern) == 0 {715 return Result{0, 0, 0}, nil716 }699- if asciiFuzzyIndex(text, pattern, caseSensitive) < 0 {717+ idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive)718+ if idx < 0 {719 return Result{-1, -1, 0}, nil720 }721 722 pidx := 085 unmodified lines808 if lenRunes < lenPattern {809 return Result{-1, -1, 0}, nil810 }811 793- if asciiFuzzyIndex(text, pattern, caseSensitive) < 0 {812+ idx, _ := asciiFuzzyIndex(text, pattern, caseSensitive)813+ if idx < 0 {814 return Result{-1, -1, 0}, nil815 }816 817 // For simplicity, only look at the bonus at the first character position167 unmodified linesmodified:src/util/chars.go+3 added-3 removed
176 unmodified lines177 }178 return runes179 }180 181-func (chars *Chars) CopyRunes(dest []rune) {181+func (chars *Chars) CopyRunes(dest []rune, from int) {182 if runes := chars.optionalRunes(); runes != nil {183- copy(dest, runes)183+ copy(dest, runes[from:])184 return185 }186- for idx, b := range chars.slice[:len(dest)] {186+ for idx, b := range chars.slice[from:][:len(dest)] {187 dest[idx] = rune(b)188 }189 }190 8 unmodified linesmodified:src/reader.go+6 added
171 unmodified lines172 atomic.StoreInt32(&r.event, int32(EvtReadNew))173 }174 } else {175 // Could not find the delimiter in the buffer176+ // NOTE: We can further optimize this by keeping track of the cursor177+ // position in the slab so that a straddling item that doesn't go178+ // beyond the boundary of a slab doesn't need to be copied to179+ // another buffer. However, the performance gain is negligible in180+ // practice (< 0.1%) and is not181+ // worth the added complexity.182 leftover = append(leftover, buf...)183 break184 }185 }76 unmodified linesmodified:CHANGELOG.md+39 added
1 unmodified line2 =========3 4 0.50.05 ------6+- Search performance optimization. You can observe 50%+ improvement in some scenarios.7+ ```sh8+ $ time wc < $DATA9+ 5520118 26862362 89748779310+11+ real 0m1.320s12+ user 0m1.236s13+ sys 0m0.075s14+15+ $ time fzf --sync --bind load:abort < $DATA16+17+ real 0m0.479s18+ user 0m0.427s19+ sys 0m0.176s20+21+ $ hyperfine -w 1 -L bin fzf-0.49.0,fzf-7ce6452,fzf-a5447b8,fzf '{bin} --filter "///" < $DATA | head -30'22+23+ Benchmark 1: fzf-0.49.0 --filter "///" < $DATA | head -3024+ Time (mean ± σ): 2.002 s ± 0.024 s [User: 14.447 s, System: 0.300 s]25+ Range (min … max): 1.964 s … 2.042 s 10 runs26+27+ Benchmark 2: fzf-7ce6452 --filter "///" < $DATA | head -3028+ Time (mean ± σ): 1.627 s ± 0.019 s [User: 10.828 s, System: 0.271 s]29+ Range (min … max): 1.596 s … 1.651 s 10 runs30+31+ Benchmark 3: fzf-a5447b8 --filter "///" < $DATA | head -3032+ Time (mean ± σ): 1.524 s ± 0.025 s [User: 9.818 s, System: 0.269 s]33+ Range (min … max): 1.478 s … 1.569 s 10 runs34+35+ Benchmark 4: fzf --filter "///" < $DATA | head -3036+ Time (mean ± σ): 1.318 s ± 0.025 s [User: 8.005 s, System: 0.262 s]37+ Range (min … max): 1.282 s … 1.366 s 10 runs38+39+ Summary40+ fzf --filter "///" < $DATA | head -30 ran41+ 1.16 ± 0.03 times faster than fzf-a5447b8 --filter "///" < $DATA | head -3042+ 1.23 ± 0.03 times faster than fzf-7ce6452 --filter "///" < $DATA | head -3043+ 1.52 ± 0.03 times faster than fzf-0.49.0 --filter "///" < $DATA | head -3044+ ```45 - Added `jump` and `jump-cancel` events that are triggered when leaving `jump` mode46 ```sh47 # Default behavior48 fzf --bind space:jump1994 unmodified lines