Replace []Result cache with bitmap cache for reduced memory usage
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Replace the per-chunk query cache from []Result slices to fixed-size bitmaps (ChunkBitmap: [16]uint64 = 128 bytes per entry). Each bit indicates whether the corresponding item in the chunk matched. This reduces cache memory by 86 times in testing: - Old []Result cache: ~22KB per chunk per query (for 500 matches) - New bitmap cache: ~262 bytes per chunk per query (fixed) With the reduced per-entry cost, queryCacheMax is raised from chunkSize/5 to chunkSize/2, allowing broader queries (up to 50% match rate) to be cached while still using far less memory.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+191 added−87 removed
- other:+191 added−87 removed
Provenance
- Commit
2f27a3e- Tree
0b37966- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
9249ea1
5 files changed+191 added−87 removed
modified:src/cache_test.go+11 added-11 removed
4 unmodified lines5 func TestChunkCache(t *testing.T) {6 cache := NewChunkCache()7 chunk1p := &Chunk{}8 chunk2p := &Chunk{count: chunkSize}9- items1 := []Result{{}}10- items2 := []Result{{}, {}}11- cache.Add(chunk1p, "foo", items1)12- cache.Add(chunk2p, "foo", items1)13- cache.Add(chunk2p, "bar", items2)9+ bm1 := ChunkBitmap{1}10+ bm2 := ChunkBitmap{1, 2}11+ cache.Add(chunk1p, "foo", bm1, 1)12+ cache.Add(chunk2p, "foo", bm1, 1)13+ cache.Add(chunk2p, "bar", bm2, 2)14 15 { // chunk1 is not full16 cached := cache.Lookup(chunk1p, "foo")17 if cached != nil {18- t.Error("Cached disabled for non-empty chunks", cached)18+ t.Error("Cached disabled for non-full chunks", cached)19 }20 }21 {22 cached := cache.Lookup(chunk2p, "foo")23- if cached == nil || len(cached) != 1 {24- t.Error("Expected 1 item cached", cached)23+ if cached == nil || cached[0] != 1 {24+ t.Error("Expected bitmap cached", cached)25 }26 }27 {28 cached := cache.Lookup(chunk2p, "bar")29- if cached == nil || len(cached) != 2 {30- t.Error("Expected 2 items cached", cached)29+ if cached == nil || cached[1] != 2 {30+ t.Error("Expected bitmap cached", cached)31 }32 }33 {34 cached := cache.Lookup(chunk1p, "foobar")35 if cached != nil {36- t.Error("Expected 0 item cached", cached)36+ t.Error("Expected nil cached", cached)37 }38 }39 }modified:src/cache.go+18 added-15 removed
1 package fzf2 3 import "sync"4 5-// queryCache associates strings to lists of items6-type queryCache map[string][]Result5+// ChunkBitmap is a bitmap with one bit per item in a chunk.6+type ChunkBitmap [chunkBitWords]uint647 8+// queryCache associates query strings to bitmaps of matching items9+type queryCache map[string]ChunkBitmap10+8-// ChunkCache associates Chunk and query string to lists of items11+// ChunkCache associates Chunk and query string to bitmaps12 type ChunkCache struct {13 mutex sync.Mutex14 cache map[*Chunk]*queryCache15 }16 unmodified lines32 }33 cc.mutex.Unlock()34 }35 33-// Add adds the list to the cache34-func (cc *ChunkCache) Add(chunk *Chunk, key string, list []Result) {35- if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {36+// Add stores the bitmap for the given chunk and key37+func (cc *ChunkCache) Add(chunk *Chunk, key string, bitmap ChunkBitmap, matchCount int) {38+ if len(key) == 0 || !chunk.IsFull() || matchCount > queryCacheMax {39 return40 }41 42 cc.mutex.Lock()3 unmodified lines46 if !ok {47 cc.cache[chunk] = &queryCache{}48 qc = cc.cache[chunk]49 }47- (*qc)[key] = list50+ (*qc)[key] = bitmap51 }52 50-// Lookup is called to lookup ChunkCache51-func (cc *ChunkCache) Lookup(chunk *Chunk, key string) []Result {53+// Lookup returns the bitmap for the exact key54+func (cc *ChunkCache) Lookup(chunk *Chunk, key string) *ChunkBitmap {55 if len(key) == 0 || !chunk.IsFull() {56 return nil57 }58 1 unmodified line60 defer cc.mutex.Unlock()61 62 qc, ok := cc.cache[chunk]63 if ok {61- list, ok := (*qc)[key]62- if ok {63- return list64+ if bm, ok := (*qc)[key]; ok {65+ return &bm66 }67 }68 return nil69 }70 71+// Search finds the bitmap for the longest prefix or suffix of the key69-func (cc *ChunkCache) Search(chunk *Chunk, key string) []Result {72+func (cc *ChunkCache) Search(chunk *Chunk, key string) *ChunkBitmap {73 if len(key) == 0 || !chunk.IsFull() {74 return nil75 }76 11 unmodified lines88 // [-------| ] | [ |-------]89 prefix := key[:len(key)-idx]90 suffix := key[idx:]91 for _, substr := range [2]string{prefix, suffix} {89- if cached, found := (*qc)[substr]; found {90- return cached92+ if bm, found := (*qc)[substr]; found {93+ return &bm94 }95 }96 }97 return nil1 unmodified linemodified:src/constants.go+3 added-2 removed
35 unmodified lines36 // Matcher37 progressMinDuration = 200 * time.Millisecond38 39 // Capacity of each chunk40- chunkSize int = 100040+ chunkSize int = 102441+ chunkBitWords = (chunkSize + 63) / 6442 43 // Pre-allocated memory slices to minimize GC44 slab16Size int = 100 * 1024 // 200KB * 32 = 12.8MB45 slab32Size int = 2048 // 8KB * 32 = 256KB46 47 // Do not cache results of low selectivity queries47- queryCacheMax int = chunkSize / 548+ queryCacheMax int = chunkSize / 249 50 // Not to cache mergers with large lists51 mergerCacheMax int = 10000052 25 unmodified linesmodified:src/pattern_test.go+118 added-1 removed
1 package fzf2 3 import (4 "reflect"5+ "runtime"6 "testing"7 8 "github.com/junegunn/fzf/src/algo"9 "github.com/junegunn/fzf/src/util"127 unmodified lines137 text: util.ToChars([]byte("junegunn")),138 origText: &origBytes,139 transformed: &transformed{pattern.revision, trans}}140 pattern.extended = extended140- matches := pattern.matchChunk(&chunk, nil, slab) // No cache141+ matches, _ := pattern.matchChunk(&chunk, nil, slab) // No cache142 if !(matches[0].item.text.ToString() == "junegunn" &&143 string(*matches[0].item.origText) == "junegunn.choi" &&144 reflect.DeepEqual((*matches[0].item.transformed).tokens, trans)) {145 t.Error("Invalid match result", matches)53 unmodified lines199 test(false, "foo '", "foo", true)200 test(false, "foo 'bar", "foo", false)201 test(false, "foo !bar", "foo", false)202 }203+204+func buildChunks(numChunks int) []*Chunk {205+ chunks := make([]*Chunk, numChunks)206+ words := []string{207+ "src/main/java/com/example/service/UserService.java",208+ "src/test/java/com/example/service/UserServiceTest.java",209+ "docs/api/reference/endpoints.md",210+ "lib/internal/utils/string_helper.go",211+ "pkg/server/http/handler/auth.go",212+ "build/output/release/app.exe",213+ "config/production/database.yml",214+ "scripts/deploy/kubernetes/setup.sh",215+ "vendor/github.com/junegunn/fzf/src/core.go",216+ "node_modules/.cache/babel/transform.js",217+ }218+ for ci := range numChunks {219+ chunks[ci] = &Chunk{count: chunkSize}220+ for i := range chunkSize {221+ text := words[(ci*chunkSize+i)%len(words)]222+ chunks[ci].items[i] = Item{text: util.ToChars([]byte(text))}223+ chunks[ci].items[i].text.Index = int32(ci*chunkSize + i)224+ }225+ }226+ return chunks227+}228+229+func buildPatternWith(cache *ChunkCache, runes []rune) *Pattern {230+ return BuildPattern(cache, make(map[string]*Pattern),231+ true, algo.FuzzyMatchV2, true, CaseSmart, false, true,232+ false, true, []Range{}, Delimiter{}, revision{}, runes, nil, 0)233+}234+235+func TestBitmapCacheBenefit(t *testing.T) {236+ numChunks := 100237+ chunks := buildChunks(numChunks)238+ queries := []string{"s", "se", "ser", "serv", "servi"}239+240+ // 1. Run all queries with shared cache (simulates incremental typing)241+ cache := NewChunkCache()242+ for _, q := range queries {243+ pat := buildPatternWith(cache, []rune(q))244+ for _, chunk := range chunks {245+ pat.Match(chunk, slab)246+ }247+ }248+249+ // 2. GC and measure memory with cache populated250+ runtime.GC()251+ runtime.GC()252+ var memWith runtime.MemStats253+ runtime.ReadMemStats(&memWith)254+255+ // 3. Clear cache, GC, measure again256+ cache.Clear()257+ runtime.GC()258+ runtime.GC()259+ var memWithout runtime.MemStats260+ runtime.ReadMemStats(&memWithout)261+262+ cacheMem := int64(memWith.Alloc) - int64(memWithout.Alloc)263+ t.Logf("Chunks: %d, Queries: %d", numChunks, len(queries))264+ t.Logf("Cache memory: %d bytes (%.1f KB)", cacheMem, float64(cacheMem)/1024)265+ t.Logf("Per-chunk-per-query: %.0f bytes", float64(cacheMem)/float64(numChunks*len(queries)))266+267+ // 4. Verify correctness: cached vs uncached produce same results268+ cache2 := NewChunkCache()269+ for _, q := range queries {270+ pat := buildPatternWith(cache2, []rune(q))271+ for _, chunk := range chunks {272+ pat.Match(chunk, slab)273+ }274+ }275+ for _, q := range queries {276+ patCached := buildPatternWith(cache2, []rune(q))277+ patFresh := buildPatternWith(NewChunkCache(), []rune(q))278+ var countCached, countFresh int279+ for _, chunk := range chunks {280+ countCached += len(patCached.Match(chunk, slab))281+ countFresh += len(patFresh.Match(chunk, slab))282+ }283+ if countCached != countFresh {284+ t.Errorf("query=%q: cached=%d, fresh=%d", q, countCached, countFresh)285+ }286+ t.Logf("query=%q: matches=%d", q, countCached)287+ }288+}289+290+func BenchmarkWithCache(b *testing.B) {291+ numChunks := 100292+ chunks := buildChunks(numChunks)293+ queries := []string{"s", "se", "ser", "serv", "servi"}294+295+ b.Run("cached", func(b *testing.B) {296+ for range b.N {297+ cache := NewChunkCache()298+ for _, q := range queries {299+ pat := buildPatternWith(cache, []rune(q))300+ for _, chunk := range chunks {301+ pat.Match(chunk, slab)302+ }303+ }304+ }305+ })306+307+ b.Run("uncached", func(b *testing.B) {308+ for range b.N {309+ for _, q := range queries {310+ cache := NewChunkCache()311+ pat := buildPatternWith(cache, []rune(q))312+ for _, chunk := range chunks {313+ pat.Match(chunk, slab)314+ }315+ }316+ }317+ })318+}modified:src/pattern.go+41 added-58 removed
298 unmodified lines299 }300 301 // Match returns the list of matches Items in the given Chunk302 func (p *Pattern) Match(chunk *Chunk, slab *util.Slab) []Result {303- // ChunkCache: Exact match303 cacheKey := p.CacheKey()304+305+ // Bitmap cache: exact match or prefix/suffix306+ var cachedBitmap *ChunkBitmap307 if p.cacheable {306- if cached := p.cache.Lookup(chunk, cacheKey); cached != nil {307- return cached308- }308+ cachedBitmap = p.cache.Lookup(chunk, cacheKey)309 }310+ if cachedBitmap == nil {311+ cachedBitmap = p.cache.Search(chunk, cacheKey)312+ }313 311- // Prefix/suffix cache312- space := p.cache.Search(chunk, cacheKey)314+ matches, bitmap := p.matchChunk(chunk, cachedBitmap, slab)315 314- matches := p.matchChunk(chunk, space, slab)315-316 if p.cacheable {317- p.cache.Add(chunk, cacheKey, matches)317+ p.cache.Add(chunk, cacheKey, bitmap, len(matches))318 }319 return matches320 }321 322-func (p *Pattern) matchChunk(chunk *Chunk, space []Result, slab *util.Slab) []Result {322+func (p *Pattern) matchChunk(chunk *Chunk, cachedBitmap *ChunkBitmap, slab *util.Slab) ([]Result, ChunkBitmap) {323 matches := []Result{}324+ var bitmap ChunkBitmap325 326 // Skip header items in chunks that contain them327 startIdx := 0328 if p.startIndex > 0 && chunk.count > 0 && chunk.items[0].Index() < p.startIndex {329 startIdx = int(p.startIndex - chunk.items[0].Index())330 if startIdx >= chunk.count {330- return matches331+ return matches, bitmap332 }333 }334 335+ hasCachedBitmap := cachedBitmap != nil336+337 // Fast path: single fuzzy term, no nth, no denylist.338 // Calls the algo function directly, bypassing MatchItem/extendedMatch/iter339 // and avoiding per-match []Offset heap allocation.340 if p.directAlgo != nil && len(p.denylist) == 0 {341 t := p.directTerm339- if space == nil {340- for idx := startIdx; idx < chunk.count; idx++ {341- res, _ := p.directAlgo(t.caseSensitive, t.normalize, p.forward,342- &chunk.items[idx].text, t.text, p.withPos, slab)343- if res.Start >= 0 {344- matches = append(matches, buildResultFromBounds(345- &chunk.items[idx], res.Score,346- int(res.Start), int(res.End), int(res.End), true))347- }342+ for idx := startIdx; idx < chunk.count; idx++ {343+ if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {344+ continue345 }349- } else {350- for _, result := range space {351- res, _ := p.directAlgo(t.caseSensitive, t.normalize, p.forward,352- &result.item.text, t.text, p.withPos, slab)353- if res.Start >= 0 {354- matches = append(matches, buildResultFromBounds(355- result.item, res.Score,356- int(res.Start), int(res.End), int(res.End), true))357- }346+ res, _ := p.directAlgo(t.caseSensitive, t.normalize, p.forward,347+ &chunk.items[idx].text, t.text, p.withPos, slab)348+ if res.Start >= 0 {349+ bitmap[idx/64] |= uint64(1) << (idx % 64)350+ matches = append(matches, buildResultFromBounds(351+ &chunk.items[idx], res.Score,352+ int(res.Start), int(res.End), int(res.End), true))353 }354 }360- return matches355+ return matches, bitmap356 }357 358 if len(p.denylist) == 0 {364- // Huge code duplication for minimizing unnecessary map lookups365- if space == nil {366- for idx := startIdx; idx < chunk.count; idx++ {367- if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {368- matches = append(matches, match)369- }370- }371- } else {372- for _, result := range space {373- if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match.item != nil {374- matches = append(matches, match)375- }376- }377- }378- return matches379- }380-381- if space == nil {359 for idx := startIdx; idx < chunk.count; idx++ {383- if _, prs := p.denylist[chunk.items[idx].Index()]; prs {360+ if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {361 continue362 }363 if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {364+ bitmap[idx/64] |= uint64(1) << (idx % 64)365 matches = append(matches, match)366 }367 }390- } else {391- for _, result := range space {392- if _, prs := p.denylist[result.item.Index()]; prs {393- continue394- }395- if match, _, _ := p.MatchItem(result.item, p.withPos, slab); match.item != nil {396- matches = append(matches, match)397- }368+ return matches, bitmap369+ }370+371+ for idx := startIdx; idx < chunk.count; idx++ {372+ if hasCachedBitmap && cachedBitmap[idx/64]&(uint64(1)<<(idx%64)) == 0 {373+ continue374 }375+ if _, prs := p.denylist[chunk.items[idx].Index()]; prs {376+ continue377+ }378+ if match, _, _ := p.MatchItem(&chunk.items[idx], p.withPos, slab); match.item != nil {379+ bitmap[idx/64] |= uint64(1) << (idx % 64)380+ matches = append(matches, match)381+ }382 }400- return matches383+ return matches, bitmap384 }385 386 // MatchItem returns the match result if the Item is a match.387 // A zero-value Result (with item == nil) indicates no match.114 unmodified lines