Improvements in performance and memory usage
Before adoption: this commit came in with the history the project adopted, so no landing records it.
I profiled fzf and it turned out that it was spending significant amount of time repeatedly converting character arrays into Unicode codepoints. This commit greatly improves search performance after the initial scan by memoizing the converted results. This commit also addresses the problem of unbounded memory usage of fzf. fzf is a short-lived process that usually processes small input, so it was implemented to cache the intermediate results very aggressively with no notion of cache expiration/eviction. I still think a proper implementation of caching scheme is definitely an overkill. Instead this commit introduces limits to the maximum size (or minimum selectivity) of the intermediate results that can be cached.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
19 files+144 added−135 removed
- other:+144 added−135 removed
Provenance
- Commit
2fe1e28- Tree
82c77b5- Author
Junegunn Choi <junegunn.c@gmail.com>- Committer
Junegunn Choi <junegunn.c@gmail.com>- Parent
288131a
19 files changed+144 added−135 removed
modified:src/algo/algo_test.go+3 added-3 removed
3 unmodified lines4 "strings"5 "testing"6 )7 8-func assertMatch(t *testing.T, fun func(bool, *string, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {8+func assertMatch(t *testing.T, fun func(bool, *[]rune, []rune) (int, int), caseSensitive bool, input string, pattern string, sidx int, eidx int) {9 if !caseSensitive {10 pattern = strings.ToLower(pattern)11 }12+ runes := []rune(input)12- s, e := fun(caseSensitive, &input, []rune(pattern))13+ s, e := fun(caseSensitive, &runes, []rune(pattern))14 if s != sidx {15 t.Errorf("Invalid start index: %d (expected: %d, %s / %s)", s, sidx, input, pattern)16 }17 if e != eidx {27 unmodified lines45 }46 47 func TestEmptyPattern(t *testing.T) {48 assertMatch(t, FuzzyMatch, true, "foobar", "", 0, 0)48- assertMatch(t, ExactMatchStrings, true, "foobar", "", 0, 0)49 assertMatch(t, ExactMatchNaive, true, "foobar", "", 0, 0)50 assertMatch(t, PrefixMatch, true, "foobar", "", 0, 0)51 assertMatch(t, SuffixMatch, true, "foobar", "", 6, 6)52 }modified:src/algo/algo.go+15 added-39 removed
1 package algo2 3 import (4- "strings"4 "unicode"5+6+ "github.com/junegunn/fzf/src/util"7 )8 9 /*10 * String matching algorithms here do not use strings.ToLower to avoid3 unmodified lines14 * In short: They try to do as little work as possible.15 */16 17 // FuzzyMatch performs fuzzy-match17-func FuzzyMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {18+func FuzzyMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {19 if len(pattern) == 0 {20 return 0, 021 }22 22- runes := []rune(*input)23-23 // 0. (FIXME) How to find the shortest match?24 // a_____b__c__abc25 // ^^^^^^^^^^ ^^^26 // 1. forward scan (abc)5 unmodified lines32 pidx := 033 sidx := -134 eidx := -135 37- for index, char := range runes {36+ for index, char := range *runes {37 // This is considerably faster than blindly applying strings.ToLower to the38 // whole string39 if !caseSensitive {40 // Partially inlining `unicode.ToLower`. Ugly, but makes a noticeable41 // difference in CPU cost. (Measured on Go 1.4.1. Also note that the Go42 // compiler as of now does not inline non-leaf functions.)43 if char >= 'A' && char <= 'Z' {44 char += 3246- runes[index] = char45+ (*runes)[index] = char46 } else if char > unicode.MaxASCII {47 char = unicode.To(unicode.LowerCase, char)49- runes[index] = char48+ (*runes)[index] = char49 }50 }51 if char == pattern[pidx] {52 if sidx < 0 {8 unmodified lines61 62 if sidx >= 0 && eidx >= 0 {63 pidx--64 for index := eidx - 1; index >= sidx; index-- {66- char := runes[index]65+ char := (*runes)[index]66 if char == pattern[pidx] {67 if pidx--; pidx < 0 {68 sidx = index69 break4 unmodified lines74 }75 return -1, -176 }77 79-// ExactMatchStrings performs exact-match using strings package.80-// Currently not used.81-func ExactMatchStrings(caseSensitive bool, input *string, pattern []rune) (int, int) {82- if len(pattern) == 0 {83- return 0, 084- }85-86- var str string87- if caseSensitive {88- str = *input89- } else {90- str = strings.ToLower(*input)91- }92-93- if idx := strings.Index(str, string(pattern)); idx >= 0 {94- prefixRuneLen := len([]rune((*input)[:idx]))95- return prefixRuneLen, prefixRuneLen + len(pattern)96- }97- return -1, -198-}99-78 // ExactMatchNaive is a basic string searching algorithm that handles case79 // sensitivity. Although naive, it still performs better than the combination80 // of strings.ToLower + strings.Index for typical fzf use cases where input81 // strings and patterns are not very long.82 //83 // We might try to implement better algorithms in the future:84 // http://en.wikipedia.org/wiki/String_searching_algorithm107-func ExactMatchNaive(caseSensitive bool, input *string, pattern []rune) (int, int) {85+func ExactMatchNaive(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {86 if len(pattern) == 0 {87 return 0, 088 }89 112- runes := []rune(*input)113- numRunes := len(runes)90+ numRunes := len(*runes)91 plen := len(pattern)92 if numRunes < plen {93 return -1, -194 }95 96 pidx := 097 for index := 0; index < numRunes; index++ {121- char := runes[index]98+ char := (*runes)[index]99 if !caseSensitive {100 if char >= 'A' && char <= 'Z' {101 char += 32102 } else if char > unicode.MaxASCII {13 unmodified lines116 return -1, -1117 }118 119 // PrefixMatch performs prefix-match143-func PrefixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {144- runes := []rune(*input)145- if len(runes) < len(pattern) {120+func PrefixMatch(caseSensitive bool, runes *[]rune, pattern []rune) (int, int) {121+ if len(*runes) < len(pattern) {122 return -1, -1123 }124 125 for index, r := range pattern {150- char := runes[index]126+ char := (*runes)[index]127 if !caseSensitive {128 char = unicode.ToLower(char)129 }130 if char != r {3 unmodified lines134 return 0, len(pattern)135 }136 137 // SuffixMatch performs suffix-match162-func SuffixMatch(caseSensitive bool, input *string, pattern []rune) (int, int) {163- runes := []rune(strings.TrimRight(*input, " "))138+func SuffixMatch(caseSensitive bool, input *[]rune, pattern []rune) (int, int) {139+ runes := util.TrimRight(input)140 trimmedLen := len(runes)141 diff := trimmedLen - len(pattern)142 if diff < 0 {143 return -1, -113 unmodified linesmodified:src/util/util.go+11 added
75 unmodified lines76 // IsTty returns true is stdin is a terminal77 func IsTty() bool {78 return int(C.isatty(C.int(os.Stdin.Fd()))) != 079 }80+81+func TrimRight(runes *[]rune) []rune {82+ var i int83+ for i = len(*runes) - 1; i >= 0; i-- {84+ char := (*runes)[i]85+ if char != ' ' && char != '\t' {86+ break87+ }88+ }89+ return (*runes)[0 : i+1]90+}modified:src/cache_test.go+1 added-1 removed
2 unmodified lines3 import "testing"4 5 func TestChunkCache(t *testing.T) {6 cache := NewChunkCache()7- chunk2 := make(Chunk, ChunkSize)7+ chunk2 := make(Chunk, chunkSize)8 chunk1p := &Chunk{}9 chunk2p := &chunk210 items1 := []*Item{&Item{}}11 items2 := []*Item{&Item{}, &Item{}}29 unmodified linesmodified:src/cache.go+6 added-6 removed
1 package fzf2 3 import "sync"4 5-// QueryCache associates strings to lists of items6-type QueryCache map[string][]*Item5+// queryCache associates strings to lists of items6+type queryCache map[string][]*Item7 8 // ChunkCache associates Chunk and query string to lists of items9 type ChunkCache struct {10 mutex sync.Mutex11- cache map[*Chunk]*QueryCache11+ cache map[*Chunk]*queryCache12 }13 14 // NewChunkCache returns a new ChunkCache15 func NewChunkCache() ChunkCache {16- return ChunkCache{sync.Mutex{}, make(map[*Chunk]*QueryCache)}16+ return ChunkCache{sync.Mutex{}, make(map[*Chunk]*queryCache)}17 }18 19 // Add adds the list to the cache20 func (cc *ChunkCache) Add(chunk *Chunk, key string, list []*Item) {21- if len(key) == 0 || !chunk.IsFull() {21+ if len(key) == 0 || !chunk.IsFull() || len(list) > queryCacheMax {22 return23 }24 25 cc.mutex.Lock()26 defer cc.mutex.Unlock()27 28 qc, ok := cc.cache[chunk]29 if !ok {30- cc.cache[chunk] = &QueryCache{}30+ cc.cache[chunk] = &queryCache{}31 qc = cc.cache[chunk]32 }33 (*qc)[key] = list34 }19 unmodified linesmodified:src/chunklist_test.go+2 added-2 removed
43 unmodified lines44 t.Error("Chunk should not have been marked full yet")45 }46 47 // Add more data48- for i := 0; i < ChunkSize*2; i++ {48+ for i := 0; i < chunkSize*2; i++ {49 cl.Push(fmt.Sprintf("item %d", i))50 }51 52 // Previous snapshot should remain the same3 unmodified lines56 57 // New snapshot58 snapshot, count = cl.Snapshot()59 if len(snapshot) != 3 || !snapshot[0].IsFull() ||60- !snapshot[1].IsFull() || snapshot[2].IsFull() || count != ChunkSize*2+2 {60+ !snapshot[1].IsFull() || snapshot[2].IsFull() || count != chunkSize*2+2 {61 t.Error("Expected two full chunks and one more chunk")62 }63 if len(*snapshot[2]) != 2 {64 t.Error("Unexpected number of items")10 unmodified linesmodified:src/chunklist.go+4 added-7 removed
1 package fzf2 3 import "sync"4 5-// Capacity of each chunk6-const ChunkSize int = 1007-8-// Chunk is a list of Item pointers whose size has the upper limit of ChunkSize5+// Chunk is a list of Item pointers whose size has the upper limit of chunkSize6 type Chunk []*Item // >>> []Item7 8 // ItemBuilder is a closure type that builds Item object from a pointer to a9 // string and an integer21 unmodified lines31 }32 33 // IsFull returns true if the Chunk is full34 func (c *Chunk) IsFull() bool {38- return len(*c) == ChunkSize35+ return len(*c) == chunkSize36 }37 38 func (cl *ChunkList) lastChunk() *Chunk {39 return cl.chunks[len(cl.chunks)-1]3 unmodified lines43 func CountItems(cs []*Chunk) int {44 if len(cs) == 0 {45 return 046 }50- return ChunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))47+ return chunkSize*(len(cs)-1) + len(*(cs[len(cs)-1]))48 }49 50 // Push adds the item to the list51 func (cl *ChunkList) Push(data string) {52 cl.mutex.Lock()53 defer cl.mutex.Unlock()54 55 if len(cl.chunks) == 0 || cl.lastChunk().IsFull() {59- newChunk := Chunk(make([]*Item, 0, ChunkSize))56+ newChunk := Chunk(make([]*Item, 0, chunkSize))57 cl.chunks = append(cl.chunks, &newChunk)58 }59 60 cl.lastChunk().push(cl.trans, &data, cl.count)25 unmodified linesmodified:src/constants.go+29 added-2 removed
1 package fzf2 3 import (4+ "time"5+6 "github.com/junegunn/fzf/src/util"7 )8 9+const (7-// Current version8-const Version = "0.9.9"10+ // Current version11+ Version = "0.9.9"12 13+ // Core14+ coordinatorDelayMax time.Duration = 100 * time.Millisecond15+ coordinatorDelayStep time.Duration = 10 * time.Millisecond16+17+ // Reader18+ defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`19+20+ // Terminal21+ initialDelay = 100 * time.Millisecond22+ spinnerDuration = 200 * time.Millisecond23+24+ // Matcher25+ progressMinDuration = 200 * time.Millisecond26+27+ // Capacity of each chunk28+ chunkSize int = 10029+30+ // Do not cache results of low selectivity queries31+ queryCacheMax int = chunkSize / 532+33+ // Not to cache mergers with large lists34+ mergerCacheMax int = 10000035+)36+37 // fzf events38 const (39 EvtReadNew util.EventType = iota40 EvtReadFin5 unmodified linesmodified:src/core.go+2 added-4 removed
32 unmodified lines33 34 "github.com/junegunn/fzf/src/util"35 )36 37-const coordinatorDelayMax time.Duration = 100 * time.Millisecond38-const coordinatorDelayStep time.Duration = 10 * time.Millisecond39-37 func initProcs() {38 runtime.GOMAXPROCS(runtime.NumCPU())39 }40 54 unmodified lines95 })96 } else {97 chunkList = NewChunkList(func(data *string, index int) *Item {98 tokens := Tokenize(data, opts.Delimiter)99+ trans := Transform(tokens, opts.WithNth)100 item := Item{103- text: Transform(tokens, opts.WithNth).whole,101+ text: joinTokens(trans),102 origText: data,103 index: uint32(index),104 colors: nil,105 rank: Rank{0, 0, uint32(index)}}142 unmodified linesmodified:src/item.go+1 added-1 removed
17 unmodified lines18 // Item represents each input line19 type Item struct {20 text *string21 origText *string22- transformed *Transformed22+ transformed *[]Token23 index uint3224 offsets []Offset25 colors []ansiOffset26 rank Rank209 unmodified linesmodified:src/matcher.go+3 added-5 removed
32 unmodified lines33 reqRetry util.EventType = iota34 reqReset35 )36 37-const (38- progressMinDuration = 200 * time.Millisecond39-)40-37 // NewMatcher returns a new Matcher38 func NewMatcher(patternBuilder func([]rune) *Pattern,39 sort bool, tac bool, eventBox *util.EventBox) *Matcher {40 return &Matcher{54 unmodified lines95 merger, cancelled = m.scan(request)96 }97 98 if !cancelled {99+ if merger.Cacheable() {103- m.mergerCache[patternString] = merger100+ m.mergerCache[patternString] = merger101+ }102 merger.final = request.final103 m.eventBox.Set(EvtSearchFin, merger)104 }105 }116 unmodified linesmodified:src/merger.go+6 added-2 removed
59 unmodified lines60 if mg.chunks != nil {61 if mg.tac {62 idx = mg.count - idx - 163 }64- chunk := (*mg.chunks)[idx/ChunkSize]65- return (*chunk)[idx%ChunkSize]64+ chunk := (*mg.chunks)[idx/chunkSize]65+ return (*chunk)[idx%chunkSize]66 }67 68 if mg.sorted {69 return mg.mergedGet(idx)11 unmodified lines81 }82 panic(fmt.Sprintf("Index out of bounds (unsorted, %d/%d)", idx, mg.count))83 }84 85+func (mg *Merger) Cacheable() bool {86+ return mg.count < mergerCacheMax87+}88+89 func (mg *Merger) mergedGet(idx int) *Item {90 for i := len(mg.merged); i <= idx; i++ {91 minRank := Rank{0, 0, 0}92 minIdx := -126 unmodified linesmodified:src/pattern_test.go+2 added-2 removed
56 unmodified lines57 defer clearPatternCache()58 clearPatternCache()59 pattern := BuildPattern(ModeExtended, CaseSmart,60 []Range{}, nil, []rune("'abc"))61- str := "aabbcc abc"62- sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &str, pattern.terms[0].text)61+ runes := []rune("aabbcc abc")62+ sidx, eidx := algo.ExactMatchNaive(pattern.caseSensitive, &runes, pattern.terms[0].text)63 if sidx != 7 || eidx != 10 {64 t.Errorf("%s / %d / %d", pattern.terms, sidx, eidx)65 }66 }50 unmodified linesmodified:src/pattern.go+9 added-10 removed
41 unmodified lines42 terms []term43 hasInvTerm bool44 delimiter *regexp.Regexp45 nth []Range46- procFun map[termType]func(bool, *string, []rune) (int, int)46+ procFun map[termType]func(bool, *[]rune, []rune) (int, int)47 }48 49 var (50 _patternCache map[string]*Pattern70 unmodified lines121 terms: terms,122 hasInvTerm: hasInvTerm,123 nth: nth,124 delimiter: delimiter,125- procFun: make(map[termType]func(bool, *string, []rune) (int, int))}125+ procFun: make(map[termType]func(bool, *[]rune, []rune) (int, int))}126 127 ptr.procFun[termFuzzy] = algo.FuzzyMatch128 ptr.procFun[termExact] = algo.ExactMatchNaive129 ptr.procFun[termPrefix] = algo.PrefixMatch169 unmodified lines299 }300 return offsets301 }302 303-func (p *Pattern) prepareInput(item *Item) *Transformed {303+func (p *Pattern) prepareInput(item *Item) *[]Token {304 if item.transformed != nil {305 return item.transformed306 }307 308- var ret *Transformed308+ var ret *[]Token309 if len(p.nth) > 0 {310 tokens := Tokenize(item.text, p.delimiter)311 ret = Transform(tokens, p.nth)312 } else {313- trans := Transformed{314- whole: item.text,315- parts: []Token{Token{text: item.text, prefixLength: 0}}}313+ runes := []rune(*item.text)314+ trans := []Token{Token{text: &runes, prefixLength: 0}}315 ret = &trans316 }317 item.transformed = ret318 return ret319 }320 322-func (p *Pattern) iter(pfun func(bool, *string, []rune) (int, int),323- inputs *Transformed, pattern []rune) (int, int) {324- for _, part := range inputs.parts {321+func (p *Pattern) iter(pfun func(bool, *[]rune, []rune) (int, int),322+ tokens *[]Token, pattern []rune) (int, int) {323+ for _, part := range *tokens {324 prefixLength := part.prefixLength325 if sidx, eidx := pfun(p.caseSensitive, part.text, pattern); sidx >= 0 {326 return sidx + prefixLength, eidx + prefixLength327 }3 unmodified linesmodified:src/reader.go-2 removed
7 unmodified lines8 9 "github.com/junegunn/fzf/src/util"10 )11 12-const defaultCommand = `find * -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null`13-12 // Reader reads from command or standard input13 type Reader struct {14 pusher func(string)15 eventBox *util.EventBox42 unmodified linesmodified:src/terminal.go+6 added-11 removed
36 unmodified lines37 count int38 progress int39 reading bool40 merger *Merger41- selected map[*string]selectedItem41+ selected map[uint32]selectedItem42 reqBox *util.EventBox43 eventBox *util.EventBox44 mutex sync.Mutex45 initFunc func()32 unmodified lines78 reqClose79 reqQuit80 )81 82-const (83- initialDelay = 100 * time.Millisecond84- spinnerDuration = 200 * time.Millisecond85-)86-82 // NewTerminal returns new Terminal object83 func NewTerminal(opts *Options, eventBox *util.EventBox) *Terminal {84 input := []rune(opts.Query)85 return &Terminal{11 unmodified lines97 expect: opts.Expect,98 pressed: 0,99 printQuery: opts.PrintQuery,100 merger: EmptyMerger,106- selected: make(map[*string]selectedItem),101+ selected: make(map[uint32]selectedItem),102 reqBox: util.NewEventBox(),103 eventBox: eventBox,104 mutex: sync.Mutex{},105 suppress: true,161 unmodified lines267 }268 }269 270 func (t *Terminal) printItem(item *Item, current bool) {276- _, selected := t.selected[item.text]271+ _, selected := t.selected[item.index]272 if current {273 C.CPrint(C.ColCursor, true, ">")274 if selected {275 C.CPrint(C.ColCurrent, true, ">")283 unmodified lines559 }560 toggle := func() {561 if t.cy < t.merger.Length() {562 item := t.merger.Get(t.cy)568- if _, found := t.selected[item.text]; !found {563+ if _, found := t.selected[item.index]; !found {564 var strptr *string565 if item.origText != nil {566 strptr = item.origText567 } else {568 strptr = item.text569 }575- t.selected[item.text] = selectedItem{time.Now(), strptr}570+ t.selected[item.index] = selectedItem{time.Now(), strptr}571 } else {577- delete(t.selected, item.text)572+ delete(t.selected, item.index)573 }574 req(reqInfo)575 }576 }190 unmodified linesmodified:src/tokenizer_test.go+15 added-15 removed
42 unmodified lines43 func TestTokenize(t *testing.T) {44 // AWK-style45 input := " abc: def: ghi "46 tokens := Tokenize(&input, nil)47- if *tokens[0].text != "abc: " || tokens[0].prefixLength != 2 {47+ if string(*tokens[0].text) != "abc: " || tokens[0].prefixLength != 2 {48 t.Errorf("%s", tokens)49 }50 51 // With delimiter52 tokens = Tokenize(&input, delimiterRegexp(":"))53- if *tokens[0].text != " abc:" || tokens[0].prefixLength != 0 {53+ if string(*tokens[0].text) != " abc:" || tokens[0].prefixLength != 0 {54 t.Errorf("%s", tokens)55 }56 }57 3 unmodified lines61 tokens := Tokenize(&input, nil)62 {63 ranges := splitNth("1,2,3")64 tx := Transform(tokens, ranges)65- if *tx.whole != "abc: def: ghi: " {65+ if *joinTokens(tx) != "abc: def: ghi: " {66 t.Errorf("%s", *tx)67 }68 }69 {70 ranges := splitNth("1..2,3,2..,1")71 tx := Transform(tokens, ranges)72- if *tx.whole != "abc: def: ghi: def: ghi: jklabc: " ||73- len(tx.parts) != 4 ||74- *tx.parts[0].text != "abc: def: " || tx.parts[0].prefixLength != 2 ||75- *tx.parts[1].text != "ghi: " || tx.parts[1].prefixLength != 14 ||76- *tx.parts[2].text != "def: ghi: jkl" || tx.parts[2].prefixLength != 8 ||77- *tx.parts[3].text != "abc: " || tx.parts[3].prefixLength != 2 {72+ if *joinTokens(tx) != "abc: def: ghi: def: ghi: jklabc: " ||73+ len(*tx) != 4 ||74+ string(*(*tx)[0].text) != "abc: def: " || (*tx)[0].prefixLength != 2 ||75+ string(*(*tx)[1].text) != "ghi: " || (*tx)[1].prefixLength != 14 ||76+ string(*(*tx)[2].text) != "def: ghi: jkl" || (*tx)[2].prefixLength != 8 ||77+ string(*(*tx)[3].text) != "abc: " || (*tx)[3].prefixLength != 2 {78 t.Errorf("%s", *tx)79 }80 }81 }1 unmodified line83 tokens := Tokenize(&input, delimiterRegexp(":"))84 {85 ranges := splitNth("1..2,3,2..,1")86 tx := Transform(tokens, ranges)87- if *tx.whole != " abc: def: ghi: def: ghi: jkl abc:" ||88- len(tx.parts) != 4 ||89- *tx.parts[0].text != " abc: def:" || tx.parts[0].prefixLength != 0 ||90- *tx.parts[1].text != " ghi:" || tx.parts[1].prefixLength != 12 ||91- *tx.parts[2].text != " def: ghi: jkl" || tx.parts[2].prefixLength != 6 ||92- *tx.parts[3].text != " abc:" || tx.parts[3].prefixLength != 0 {87+ if *joinTokens(tx) != " abc: def: ghi: def: ghi: jkl abc:" ||88+ len(*tx) != 4 ||89+ string(*(*tx)[0].text) != " abc: def:" || (*tx)[0].prefixLength != 0 ||90+ string(*(*tx)[1].text) != " ghi:" || (*tx)[1].prefixLength != 12 ||91+ string(*(*tx)[2].text) != " def: ghi: jkl" || (*tx)[2].prefixLength != 6 ||92+ string(*(*tx)[3].text) != " abc:" || (*tx)[3].prefixLength != 0 {93 t.Errorf("%s", *tx)94 }95 }96 }5 unmodified linesmodified:src/tokenizer.go+21 added-23 removed
14 unmodified lines15 begin int16 end int17 }18 19-// Transformed holds the result of tokenization and transformation20-type Transformed struct {21- whole *string22- parts []Token23-}24-19 // Token contains the tokenized part of the strings and its prefix length20 type Token struct {27- text *string21+ text *[]rune22 prefixLength int23 }24 25 func newRange(begin int, end int) Range {48 unmodified lines74 prefixLength := begin75 for idx, token := range tokens {76 // Need to define a new local variable instead of the reused token to take77 // the pointer to it84- str := token85- ret[idx] = Token{text: &str, prefixLength: prefixLength}78+ runes := []rune(token)79+ ret[idx] = Token{text: &runes, prefixLength: prefixLength}80 prefixLength += len([]rune(token))81 }82 return ret83 }51 unmodified lines135 tokens := delimiter.FindAllString(*str, -1)136 return withPrefixLengths(tokens, 0)137 }138 145-func joinTokens(tokens []Token) string {139+func joinTokens(tokens *[]Token) *string {140 ret := ""147- for _, token := range tokens {148- ret += *token.text141+ for _, token := range *tokens {142+ ret += string(*token.text)143 }150- return ret144+ return &ret145 }146 147+func joinTokensAsRunes(tokens *[]Token) *[]rune {148+ ret := []rune{}149+ for _, token := range *tokens {150+ ret = append(ret, *token.text...)151+ }152+ return &ret153+}154+155 // Transform is used to transform the input when --with-nth option is given154-func Transform(tokens []Token, withNth []Range) *Transformed {156+func Transform(tokens []Token, withNth []Range) *[]Token {157 transTokens := make([]Token, len(withNth))158 numTokens := len(tokens)157- whole := ""159 for idx, r := range withNth {159- part := ""160+ part := []rune{}161 minIdx := 0162 if r.begin == r.end {163 idx := r.begin164 if idx == rangeEllipsis {164- part += joinTokens(tokens)165+ part = append(part, *joinTokensAsRunes(&tokens)...)166 } else {167 if idx < 0 {168 idx += numTokens + 1169 }170 if idx >= 1 && idx <= numTokens {171 minIdx = idx - 1171- part += *tokens[idx-1].text172+ part = append(part, *tokens[idx-1].text...)173 }174 }175 } else {176 var begin, end int18 unmodified lines195 }196 minIdx = util.Max(0, begin-1)197 for idx := begin; idx <= end; idx++ {198 if idx >= 1 && idx <= numTokens {198- part += *tokens[idx-1].text199+ part = append(part, *tokens[idx-1].text...)200 }201 }202 }202- whole += part203 var prefixLength int204 if minIdx < numTokens {205 prefixLength = tokens[minIdx].prefixLength206 } else {207 prefixLength = 0208 }209 transTokens[idx] = Token{&part, prefixLength}210 }211- return &Transformed{212- whole: &whole,213- parts: transTokens}211+ return &transTokens212 }modified:CHANGELOG.md+8 added
1 CHANGELOG2 =========3 4+0.9.105+------6+7+### Improvements8+9+- Performance optimization10+- Less aggressive memoization to limit memory usage11+12 0.9.913 -----14 15 ### New features132 unmodified lines