-
Notifications
You must be signed in to change notification settings - Fork 299
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #85 from nhooyr/poolbuf
Pool buffers in wspb and wsjson
- Loading branch information
Showing
4 changed files
with
109 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
package bpool | ||
|
||
import ( | ||
"bytes" | ||
"sync" | ||
) | ||
|
||
var bpool sync.Pool | ||
|
||
// Get returns a buffer from the pool or creates a new one if | ||
// the pool is empty. | ||
func Get() *bytes.Buffer { | ||
b, ok := bpool.Get().(*bytes.Buffer) | ||
if !ok { | ||
b = &bytes.Buffer{} | ||
} | ||
return b | ||
} | ||
|
||
// Put returns a buffer into the pool. | ||
func Put(b *bytes.Buffer) { | ||
b.Reset() | ||
bpool.Put(b) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
package bpool | ||
|
||
import ( | ||
"strconv" | ||
"sync" | ||
"testing" | ||
) | ||
|
||
func BenchmarkSyncPool(b *testing.B) { | ||
sizes := []int{ | ||
2, | ||
16, | ||
32, | ||
64, | ||
128, | ||
256, | ||
512, | ||
4096, | ||
16384, | ||
} | ||
for _, size := range sizes { | ||
b.Run(strconv.Itoa(size), func(b *testing.B) { | ||
b.Run("allocate", func(b *testing.B) { | ||
b.ReportAllocs() | ||
for i := 0; i < b.N; i++ { | ||
buf := make([]byte, size) | ||
_ = buf | ||
} | ||
}) | ||
b.Run("pool", func(b *testing.B) { | ||
b.ReportAllocs() | ||
|
||
p := sync.Pool{} | ||
|
||
b.ResetTimer() | ||
for i := 0; i < b.N; i++ { | ||
buf := p.Get() | ||
if buf == nil { | ||
buf = make([]byte, size) | ||
} | ||
|
||
p.Put(buf) | ||
} | ||
}) | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters