difference between encoding/gob and encoding/json

2020-06-09 06:53发布

问题:

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?

回答1:

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


回答2:

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.