Skip to content

Instantly share code, notes, and snippets.

@iwanbk
Created June 8, 2018 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwanbk/afd85252c184a024aa22b31c860234b3 to your computer and use it in GitHub Desktop.
Save iwanbk/afd85252c184a024aa22b31c860234b3 to your computer and use it in GitHub Desktop.
json serialization benchmark
package main
import (
"encoding/json"
"testing"
)
func BenchmarkMapNakedInterface(b *testing.B) {
m := map[string]interface{}{
"col1": "val1",
"col2": "val2",
"col3": "val3",
"col4": "val4",
"col5": "val5",
"col6": "val6",
"col7": "val4",
"col8": "val5",
"col9": "val6",
}
for n := 0; n < b.N; n++ {
_, err := json.Marshal(m)
if err != nil {
b.Fatalf("err:%v", err)
}
}
}
func BenchmarkMapString(b *testing.B) {
m := map[string]string{
"col1": "val1",
"col2": "val2",
"col3": "val3",
"col4": "val4",
"col5": "val5",
"col6": "val6",
"col7": "val4",
"col8": "val5",
"col9": "val6",
}
for n := 0; n < b.N; n++ {
_, err := json.Marshal(m)
if err != nil {
b.Fatalf("err:%v", err)
}
}
}
type data struct {
Col1 string
Col2 string
Col3 string
Col4 string
Col5 string
Col6 string
Col7 string
Col8 string
Col9 string
}
func BenchmarkStruct(b *testing.B) {
d := data{
Col1: "val1",
Col2: "val2",
Col3: "val3",
Col4: "val4",
Col5: "val5",
Col6: "val6",
Col7: "val4",
Col8: "val5",
Col9: "val6",
}
for n := 0; n < b.N; n++ {
_, err := json.Marshal(d)
if err != nil {
b.Fatalf("err:%v", err)
}
}
}
@iwanbk
Copy link
Author

iwanbk commented Jun 8, 2018

$ go test -bench .
goos: darwin
goarch: amd64
pkg: github.com/iwanbk/playground/golang/interface
BenchmarkMapNakedInterface-4      200000              5774 ns/op
BenchmarkMapString-4              300000              4888 ns/op
BenchmarkStruct-4                1000000              1529 ns/op
PASS
ok      github.com/iwanbk/playground/golang/interface   4.291s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment