encoding/gob 和 encoding/json 之间的区别

difference between encoding/gob and encoding/json

我正在用 Go 编写一个应用程序,它使用 encoding/gob 在节点之间通过 UDP 发送结构和切片。它工作正常,但我注意到 encoding/json 也有类似的 API。搜索并找到此信息(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.

有人可以向我解释一个是否比另一个更有效,并且通常比较什么时候选择什么?另外,如果我需要与非 Go 应用程序交互,我想 json 会是首选?

Package encoding/gob 基本上是 Go 特定的,不能与其他语言一起使用,但它非常高效(快速并生成小数据)并且可以正确编组和解组更多数据结构。通过 JSON.

通常更容易与其他工具交互

在 Go 程序之间进行通信时,Gob 更受欢迎。但是,gob 目前仅在 Go 中受支持,好吧,C,所以只有在您确定没有任何其他编程语言编写的程序会尝试解码这些值时才使用它。

就性能而言,至少在我的机器上,Gob 远远优于 JSON。 Test file(放在你的 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