【问题标题】:difference between encoding/gob and encoding/jsonencoding/gob 和 encoding/json 的区别
【发布时间】:2017-05-01 23:00:18
【问题描述】:

我正在用 Go 编写一个应用程序,它使用 encoding/gob 在节点之间通过 UDP 发送结构和切片。它工作正常,但我注意到 encoding/json 也有类似的 API。搜索了一下,发现了这个信息(https://golang.org/pkg/encoding/):

gob 包 gob 管理 gob 流 - 交换的二进制值 编码器(发送器)和解码器(接收器)之间。
json 包 json 实现了 JSON 的编码和解码,定义在 RFC 4627。

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

【问题讨论】:

标签: json go encoding gob


【解决方案1】:

在 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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-12
      • 2021-04-15
      • 2020-10-12
      • 1970-01-01
      • 2016-09-16
      • 2021-04-13
      • 1970-01-01
      • 2020-10-05
      相关资源
      最近更新 更多