Last active
August 29, 2015 14:15
-
-
Save cubicdaiya/a523cada9d9693c217e6 to your computer and use it in GitHub Desktop.
JSON encode/decode benchmark with encoding/json and ugorji/go/codec
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
$ go test -bench . -benchtime 1s | |
PASS | |
BenchmarkMarshal 500000 2989 ns/op | |
BenchmarkCodecJsonBufEncode 1000000 2245 ns/op | |
BenchmarkCodecJsonIOEncode 1000000 2376 ns/op | |
$ |
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
package main | |
import ( | |
"bufio" | |
"bytes" | |
"encoding/json" | |
_ "fmt" | |
"github.com/ugorji/go/codec" | |
"testing" | |
"time" | |
) | |
type Entry struct { | |
Type string `json:"type"` | |
Time string `json:"time"` | |
URI string `json:"uri"` | |
Method string `json:"method"` | |
Proto string `json:"proto"` | |
ContentLength int64 `json:"content_length"` | |
} | |
func makeEntry() Entry { | |
log := &Entry{ | |
Type: "accepted-request", | |
Time: time.Now().Format("2006/01/02 15:04:05 MST"), | |
URI: "/push", | |
Method: "POST", | |
Proto: "HTTP/1.1", | |
ContentLength: 1024, | |
} | |
return *log | |
} | |
func BenchmarkMarshal(b *testing.B) { | |
log := makeEntry() | |
for i := 0; i < b.N; i++ { | |
_, _ = json.Marshal(log) | |
} | |
} | |
func BenchmarkCodecJsonBufEncode(b *testing.B) { | |
var buf []byte = make([]byte, 0, 64) | |
var h codec.Handle = new(codec.JsonHandle) | |
var enc *codec.Encoder = codec.NewEncoderBytes(&buf, h) | |
log := makeEntry() | |
for i := 0; i < b.N; i++ { | |
_ = enc.Encode(log) | |
} | |
} | |
func BenchmarkCodecJsonIOEncode(b *testing.B) { | |
var buf bytes.Buffer | |
var h codec.Handle = new(codec.JsonHandle) | |
var bw = bufio.NewWriter(&buf) | |
var enc *codec.Encoder = codec.NewEncoder(bw, h) | |
log := makeEntry() | |
for i := 0; i < b.N; i++ { | |
_ = enc.Encode(log) | |
bw.Flush() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment