Created
December 16, 2016 08:57
-
-
Save thehowl/85057ad21697160e81ac42bf358a322a to your computer and use it in GitHub Desktop.
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 ( | |
"testing" | |
"encoding/json" | |
"encoding/gob" | |
"bytes" | |
) | |
// initialisation | |
type SampleStruct struct { | |
A string | |
B int | |
C float64 | |
D bool | |
} | |
var encValue = SampleStruct{ | |
"The lazy fox jumps over the lazy dog", | |
42, | |
13.37, | |
true, | |
} | |
func init() { | |
gob.Register(SampleStruct{}) | |
} | |
type FakeWriter struct{} | |
func (FakeWriter) Write([]byte) (int, error) { | |
return 0, nil | |
} | |
var decodeInto SampleStruct | |
// gob encoding | |
var gobEncoder = gob.NewEncoder(FakeWriter{}) | |
func BenchmarkGobEncoding(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
gobEncoder.Encode(encValue) | |
} | |
} | |
// json encoding | |
var jsonEncoder = json.NewEncoder(FakeWriter{}) | |
func BenchmarkJSONEncoding(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
jsonEncoder.Encode(encValue) | |
} | |
} | |
// gob decoding | |
var gobReader = bytes.NewReader(gobTestValue) | |
var gobDecoder = gob.NewDecoder(gobReader) | |
var gobTestValue = []byte{0x32, 0xff, 0x81, 0x3, 0x1, 0x1, 0xc, 0x53, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x53, 0x74, 0x72, 0x75, 0x63, 0x74, 0x1, 0xff, 0x82, 0x0, 0x1, 0x4, 0x1, 0x1, 0x41, 0x1, 0xc, | |
0x0, 0x1, 0x1, 0x42, 0x1, 0x4, 0x0, 0x1, 0x1, 0x43, 0x1, 0x8, 0x0, 0x1, 0x1, 0x44, 0x1, 0x2, 0x0, 0x0, 0x0, 0x11, 0xff, 0x82, 0x1, 0xc, 0x44, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x20, 0x74, | |
0x65, 0x73, 0x74, 0x0} | |
func BenchmarkGobDecoding(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
gobDecoder.Decode(&decodeInto) | |
gobReader.Reset(gobTestValue) | |
} | |
} | |
// json decoding | |
var jsonReader = bytes.NewReader(jsonTestValue) | |
var jsonDecoder = json.NewDecoder(jsonReader) | |
var jsonTestValue = []byte{0x7b, 0x22, 0x41, 0x22, 0x3a, 0x22, 0x44, 0x65, 0x63, 0x6f, 0x64, 0x65, 0x72, 0x20, 0x74, 0x65, 0x73, 0x74, 0x22, 0x2c, 0x22, 0x42, 0x22, 0x3a, 0x30, 0x2c, 0x22, 0x43, | |
0x22, 0x3a, 0x30, 0x2c, 0x22, 0x44, 0x22, 0x3a, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x7d, 0xa} | |
func BenchmarkJSONDecoding(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
jsonDecoder.Decode(&decodeInto) | |
jsonReader.Reset(jsonTestValue) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment