I am writing an application in Go which uses encoding/gob to send structures and slices over UDP between nodes. It works fine but I notice that encoding/json also has the similar API. Searched and found this information(https://golang.org/pkg/encoding/):
gob Package gob manages streams of gobs - binary values exchanged between an Encoder (transmitter) and a Decoder (receiver).
json Package json implements encoding and decoding of JSON as defined in RFC 4627.
Can someone explain to me whether one is more efficient than the other and in general compare when to choose what? Also if I need to interface with a non-Go application, I guess json would be preferred?
Gob is much more preferred when communicating between Go programs. However, gob is currently supported only in Go and, well, C, so only ever use that when you're sure no program written in any other programming language will try to decode the values.
When it comes to performance, at least on my machine, Gob outperforms JSON by a long shot. Test file (put in a folder on its own under your GOPATH)
$ go test -bench=.
testing: warning: no tests to run
BenchmarkGobEncoding-4 1000000 1172 ns/op
BenchmarkJSONEncoding-4 500000 2322 ns/op
BenchmarkGobDecoding-4 5000000 486 ns/op
BenchmarkJSONDecoding-4 500000 3228 ns/op
PASS
ok testencoding 6.814s
Package encoding/gob is basically Go specific and unusable with other languages but it is very efficient (fast and generates small data) and can properly marshal and unmarshal more data structures. Interfacing with other tools is often easier via JSON.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With