Created
July 11, 2018 06:57
-
-
Save yowcow/66d06d1cebba3da6bcca0ee8be384ebe to your computer and use it in GitHub Desktop.
JSON unmarshal serial v. parallel
This file contains hidden or 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 ( | |
"encoding/json" | |
"sync" | |
"testing" | |
) | |
var jsonStr = `{"url":"http://hoge","score":123,"map":{"123":123,"234":234}}` | |
type Map map[string]int | |
type Source struct { | |
URL string `json:"url"` | |
Score int `json:"score"` | |
Map Map `json:"map"` | |
} | |
func BenchmarkSerial_JSON_Unmarshal(b *testing.B) { | |
jsonBytes := []byte(jsonStr) | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
var src Source | |
json.Unmarshal(jsonBytes, &src) | |
} | |
b.StopTimer() | |
} | |
func BenchmarkParallel_JSON_Unmarshal(b *testing.B) { | |
jsonBytes := []byte(jsonStr) | |
var wg sync.WaitGroup | |
out := make(chan []byte) | |
wg.Add(5) | |
for i := 0; i < 5; i++ { | |
go func(w *sync.WaitGroup, in <-chan []byte) { | |
defer w.Done() | |
for input := range in { | |
var src Source | |
json.Unmarshal(input, &src) | |
} | |
}(&wg, out) | |
} | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
out <- jsonBytes | |
} | |
b.StopTimer() | |
close(out) | |
wg.Wait() | |
} | |
/** | |
BenchmarkSerial_JSON_Unmarshal-4 300000 4265 ns/op | |
BenchmarkParallel_JSON_Unmarshal-4 500000 3024 ns/op | |
*/ |
Author
yowcow
commented
Jul 11, 2018
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment