Skip to content

Instantly share code, notes, and snippets.

@phemmer
Last active August 29, 2015 14:20
Show Gist options
  • Select an option

  • Save phemmer/69cbd7be157e1c90c4b1 to your computer and use it in GitHub Desktop.

Select an option

Save phemmer/69cbd7be157e1c90c4b1 to your computer and use it in GitHub Desktop.
golang json unmarshal benchmarks
package main
import (
"encoding/json"
"fmt"
"testing"
)
type elements map[string]int
var unmarshalled elements
func genJSON(size int) []byte {
data := make([]byte, 0, size+20) // we'll go over just a small bit
data = append(data, '{')
i := 0
for len(data) <= size {
data = append(data, []byte(fmt.Sprintf(`"%d": %d,`, i, i))...)
i++
}
data[len(data)-1] = '}'
return data
}
func benchmark(b *testing.B, size int) {
b.StopTimer()
data := genJSON(size)
b.StartTimer()
for i := 0; i < b.N; i++ {
unmarshalled = elements{}
err := json.Unmarshal(data, &unmarshalled)
if err != nil {
b.Fatal(err)
}
}
}
func Benchmark16k(b *testing.B) {
benchmark(b, 16*1024)
}
func Benchmark32k(b *testing.B) {
benchmark(b, 32*1024)
}
func Benchmark64k(b *testing.B) {
benchmark(b, 64*1024)
}
func Benchmark128k(b *testing.B) {
benchmark(b, 128*1024)
}
# go test -bench=. -v ./...
testing: warning: no tests to run
PASS
Benchmark16k 1000 1911398 ns/op
Benchmark32k 500 3439059 ns/op
Benchmark64k 200 6448114 ns/op
Benchmark128k 100 13139580 ns/op
ok tmp/8pg 7.482s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment