Skip to content

Commit

Permalink
shell: reduce allocations in Quote
Browse files Browse the repository at this point in the history
Grow the quote buffer to a plausible baseline before filling.
Add BenchmarkQuote.

Quote-10 │ before.txt  │ after.txt  | vs base
         │ sec/op      │ sec/op     |
         | 778.1µ      | 801.0µ     | +2.95%

         │ B/op        │ B/op       |
         | 711.9Ki     | 512.0Ki    | -28.08%

         │ allocs/op   │ allocs/op  |
         | 14.000      | 3.000      | -78.57%
  • Loading branch information
creachadair committed Aug 30, 2024
1 parent 57b02d7 commit c894905
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
28 changes: 28 additions & 0 deletions shell/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,4 +76,32 @@ func BenchmarkSplit(b *testing.B) {
}
}

func BenchmarkQuote(b *testing.B) {
const alphabet = "abcdefghijklmnopqrstuvwxyz0123456789 \t\n\n\n"
src := rand.NewSource(67890)
r := rand.New(src)

var buf bytes.Buffer
for range 100000 {
switch v := r.Float64(); {
case v < 0.5:
buf.WriteByte('\'')
case v < 0.1:
buf.WriteByte('"')
case v < 0.15:
buf.WriteByte('\\')
default:
pos := math.Ceil(r.Float64()*float64(len(alphabet))) - 1
buf.WriteByte(alphabet[int(pos)])
}
}

input := buf.String()
b.ResetTimer()

for range b.N {
shell.Quote(input)
}
}

func ignore(string) bool { return true }
1 change: 1 addition & 0 deletions shell/shell.go
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ func quote(s string, buf *bytes.Buffer) string {
}

buf.Reset()
buf.Grow(len(s))
inq := false
for i := range len(s) {
ch := s[i]
Expand Down

0 comments on commit c894905

Please sign in to comment.