Skip to content

Commit

Permalink
Merge pull request #2 from nuss-justin/buffer-pool
Browse files Browse the repository at this point in the history
Pool buffers for quoted strings and byte slices
  • Loading branch information
ChrisHines committed Jun 1, 2016
2 parents 538518f + 8e11237 commit d432719
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 5 deletions.
1 change: 0 additions & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
language: go
sudo: false
go:
- 1.2
- 1.3
- 1.4
- 1.5
Expand Down
28 changes: 24 additions & 4 deletions jsonstring.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"bytes"
"io"
"strconv"
"sync"
"unicode"
"unicode/utf16"
"unicode/utf8"
Expand All @@ -17,9 +18,24 @@ import (

var hex = "0123456789abcdef"

var bufferPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}

func getBuffer() *bytes.Buffer {
return bufferPool.Get().(*bytes.Buffer)
}

func poolBuffer(buf *bytes.Buffer) {
buf.Reset()
bufferPool.Put(buf)
}

// NOTE: keep in sync with writeQuotedBytes below.
func writeQuotedString(w io.Writer, s string) (int, error) {
buf := &bytes.Buffer{}
buf := getBuffer()
buf.WriteByte('"')
start := 0
for i := 0; i < len(s); {
Expand Down Expand Up @@ -70,12 +86,14 @@ func writeQuotedString(w io.Writer, s string) (int, error) {
buf.WriteString(s[start:])
}
buf.WriteByte('"')
return w.Write(buf.Bytes())
n, err := w.Write(buf.Bytes())
poolBuffer(buf)
return n, err
}

// NOTE: keep in sync with writeQuoteString above.
func writeQuotedBytes(w io.Writer, s []byte) (int, error) {
buf := &bytes.Buffer{}
buf := getBuffer()
buf.WriteByte('"')
start := 0
for i := 0; i < len(s); {
Expand Down Expand Up @@ -126,7 +144,9 @@ func writeQuotedBytes(w io.Writer, s []byte) (int, error) {
buf.Write(s[start:])
}
buf.WriteByte('"')
return w.Write(buf.Bytes())
n, err := w.Write(buf.Bytes())
poolBuffer(buf)
return n, err
}

// getu4 decodes \uXXXX from the beginning of s, returning the hex value,
Expand Down

0 comments on commit d432719

Please sign in to comment.