2016-12-16 07:39
浏览 341

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

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(

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-golang application, I guess json would be preferred?

图片转代码服务由CSDN问答提供 功能建议

我正在GO中编写一个应用程序,该应用程序使用编码/对象在节点之间通过UDP发送结构和切片。 它工作正常,但我注意到encoding / json也具有类似的API。 搜索并找到此信息( ):

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

有人可以向我解释一种方法是否比另一种方法更有效,并且通常比较何时选择哪种方法 ? 另外,如果我需要与非golang应用程序进行接口,我猜会首选json吗?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsjxgu4759 2016-12-16 09:04

    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
    ok      testencoding    6.814s
    打赏 评论
  • dsrjs86444 2016-12-16 09:01

    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.

    打赏 评论

相关推荐 更多相似问题