difference between encoding/gob and encoding/json
Asked Answered
A

2

18

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?

Aubervilliers answered 16/12, 2016 at 7:39 Comment(1)
An example when gob "wins" over json: How to unmarshal from interface{} to interface{} in Go. Also see interesting / related questions: Is encoding/gob deterministic?; and Efficient Go serialization of struct to diskRaymundorayna
T
29

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
Topographer answered 16/12, 2016 at 9:4 Comment(0)
P
14

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.

Postpone answered 16/12, 2016 at 9:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.