Debian Codegraph @

README.md

raw
1 # easyjson [![Build Status](https://github.com/mailru/easyjson/actions/workflows/easyjson.yml/badge.svg)](https://github.com/mailru/easyjson/actions/workflows/easyjson.yml) [![Go Report Card](https://goreportcard.com/badge/github.com/mailru/easyjson)](https://goreportcard.com/report/github.com/mailru/easyjson)
2
3 Package easyjson provides a fast and easy way to marshal/unmarshal Go structs
4 to/from JSON without the use of reflection. In performance tests, easyjson
5 outperforms the standard `encoding/json` package by a factor of 4-5x, and other
6 JSON encoding packages by a factor of 2-3x.
7
8 easyjson aims to keep generated Go code simple enough so that it can be easily
9 optimized or fixed. Another goal is to provide users with the ability to
10 customize the generated code by providing options not available with the
11 standard `encoding/json` package, such as generating "snake_case" names or
12 enabling `omitempty` behavior by default.
13
14 ## Usage
15 ### Install:
16 ```sh
17 # for Go < 1.17
18 go get -u github.com/mailru/easyjson/...
19 ```
20 #### or
21 ```sh
22 # for Go >= 1.17
23 go get github.com/mailru/easyjson && go install github.com/mailru/easyjson/...@latest
24 ```
25 ### Run:
26 ```sh
27 easyjson -all <file>.go
28 ```
29
30 The above will generate `<file>_easyjson.go` containing the appropriate marshaler and
31 unmarshaler funcs for all structs contained in `<file>.go`.
32
33 Please note that easyjson requires a full Go build environment and the `GOPATH`
34 environment variable to be set. This is because easyjson code generation
35 invokes `go run` on a temporary file (an approach to code generation borrowed
36 from [ffjson](https://github.com/pquerna/ffjson)).
37
38 ### Serialize
39 ```go
40 someStruct := &SomeStruct{Field1: "val1", Field2: "val2"}
41 rawBytes, err := easyjson.Marshal(someStruct)
42 ```
43
44 ### Deserialize
45 ```go
46 someStruct := &SomeStruct{}
47 err := easyjson.Unmarshal(rawBytes, someStruct)
48 ```
49
50 Please see the [GoDoc](https://godoc.org/github.com/mailru/easyjson)
51 for more information and features.
52 ## Options
53 ```txt
54 Usage of easyjson:
55 -all
56 generate marshaler/unmarshalers for all structs in a file
57 -build_tags string
58 build tags to add to generated file
59 -gen_build_flags string
60 build flags when running the generator while bootstrapping
61 -byte
62 use simple bytes instead of Base64Bytes for slice of bytes
63 -leave_temps
64 do not delete temporary files
65 -no_std_marshalers
66 don't generate MarshalJSON/UnmarshalJSON funcs
67 -noformat
68 do not run 'gofmt -w' on output file
69 -omit_empty
70 omit empty fields by default
71 -output_filename string
72 specify the filename of the output
73 -pkg
74 process the whole package instead of just the given file
75 -snake_case
76 use snake_case names instead of CamelCase by default
77 -lower_camel_case
78 use lowerCamelCase instead of CamelCase by default
79 -stubs
80 only generate stubs for marshaler/unmarshaler funcs
81 -disallow_unknown_fields
82 return error if some unknown field in json appeared
83 -disable_members_unescape
84 disable unescaping of \uXXXX string sequences in member names
85 ```
86
87 Using `-all` will generate marshalers/unmarshalers for all Go structs in the
88 file excluding those structs whose preceding comment starts with `easyjson:skip`.
89 For example:
90
91 ```go
92 //easyjson:skip
93 type A struct {}
94 ```
95
96 If `-all` is not provided, then only those structs whose preceding
97 comment starts with `easyjson:json` will have marshalers/unmarshalers
98 generated. For example:
99
100 ```go
101 //easyjson:json
102 type A struct {}
103 ```
104
105 Additional option notes:
106
107 * `-snake_case` tells easyjson to generate snake\_case field names by default
108 (unless overridden by a field tag). The CamelCase to snake\_case conversion
109 algorithm should work in most cases (ie, HTTPVersion will be converted to
110 "http_version").
111
112 * `-build_tags` will add the specified build tags to generated Go sources.
113
114 * `-gen_build_flags` will execute the easyjson bootstapping code to launch the
115 actual generator command with provided flags. Multiple arguments should be
116 separated by space e.g. `-gen_build_flags="-mod=mod -x"`.
117
118 ## Structure json tag options
119
120 Besides standard json tag options like 'omitempty' the following are supported:
121
122 * 'nocopy' - disables allocation and copying of string values, making them
123 refer to original json buffer memory. This works great for short lived
124 objects which are not hold in memory after decoding and immediate usage.
125 Note if string requires unescaping it will be processed as normally.
126 * 'intern' - string "interning" (deduplication) to save memory when the very
127 same string dictionary values are often met all over the structure.
128 See below for more details.
129
130 ## Generated Marshaler/Unmarshaler Funcs
131
132 For Go struct types, easyjson generates the funcs `MarshalEasyJSON` /
133 `UnmarshalEasyJSON` for marshaling/unmarshaling JSON. In turn, these satisfy
134 the `easyjson.Marshaler` and `easyjson.Unmarshaler` interfaces and when used in
135 conjunction with `easyjson.Marshal` / `easyjson.Unmarshal` avoid unnecessary
136 reflection / type assertions during marshaling/unmarshaling to/from JSON for Go
137 structs.
138
139 easyjson also generates `MarshalJSON` and `UnmarshalJSON` funcs for Go struct
140 types compatible with the standard `json.Marshaler` and `json.Unmarshaler`
141 interfaces. Please be aware that using the standard `json.Marshal` /
142 `json.Unmarshal` for marshaling/unmarshaling will incur a significant
143 performance penalty when compared to using `easyjson.Marshal` /
144 `easyjson.Unmarshal`.
145
146 Additionally, easyjson exposes utility funcs that use the `MarshalEasyJSON` and
147 `UnmarshalEasyJSON` for marshaling/unmarshaling to and from standard readers
148 and writers. For example, easyjson provides `easyjson.MarshalToHTTPResponseWriter`
149 which marshals to the standard `http.ResponseWriter`. Please see the [GoDoc
150 listing](https://godoc.org/github.com/mailru/easyjson) for the full listing of
151 utility funcs that are available.
152
153 ## Controlling easyjson Marshaling and Unmarshaling Behavior
154
155 Go types can provide their own `MarshalEasyJSON` and `UnmarshalEasyJSON` funcs
156 that satisfy the `easyjson.Marshaler` / `easyjson.Unmarshaler` interfaces.
157 These will be used by `easyjson.Marshal` and `easyjson.Unmarshal` when defined
158 for a Go type.
159
160 Go types can also satisfy the `easyjson.Optional` interface, which allows the
161 type to define its own `omitempty` logic.
162
163 ## Type Wrappers
164
165 easyjson provides additional type wrappers defined in the `easyjson/opt`
166 package. These wrap the standard Go primitives and in turn satisfy the
167 easyjson interfaces.
168
169 The `easyjson/opt` type wrappers are useful when needing to distinguish between
170 a missing value and/or when needing to specifying a default value. Type
171 wrappers allow easyjson to avoid additional pointers and heap allocations and
172 can significantly increase performance when used properly.
173
174 ## Memory Pooling
175
176 easyjson uses a buffer pool that allocates data in increasing chunks from 128
177 to 32768 bytes. Chunks of 512 bytes and larger will be reused with the help of
178 `sync.Pool`. The maximum size of a chunk is bounded to reduce redundant memory
179 allocation and to allow larger reusable buffers.
180
181 easyjson's custom allocation buffer pool is defined in the `easyjson/buffer`
182 package, and the default behavior pool behavior can be modified (if necessary)
183 through a call to `buffer.Init()` prior to any marshaling or unmarshaling.
184 Please see the [GoDoc listing](https://godoc.org/github.com/mailru/easyjson/buffer)
185 for more information.
186
187 ## String interning
188
189 During unmarshaling, `string` field values can be optionally
190 [interned](https://en.wikipedia.org/wiki/String_interning) to reduce memory
191 allocations and usage by deduplicating strings in memory, at the expense of slightly
192 increased CPU usage.
193
194 This will work effectively only for `string` fields being decoded that have frequently
195 the same value (e.g. if you have a string field that can only assume a small number
196 of possible values).
197
198 To enable string interning, add the `intern` keyword tag to your `json` tag on `string`
199 fields, e.g.:
200
201 ```go
202 type Foo struct {
203 UUID string `json:"uuid"` // will not be interned during unmarshaling
204 State string `json:"state,intern"` // will be interned during unmarshaling
205 }
206 ```
207
208 ## Issues, Notes, and Limitations
209
210 * easyjson is still early in its development. As such, there are likely to be
211 bugs and missing features when compared to `encoding/json`. In the case of a
212 missing feature or bug, please create a GitHub issue. Pull requests are
213 welcome!
214
215 * Unlike `encoding/json`, object keys are case-sensitive. Case-insensitive
216 matching is not currently provided due to the significant performance hit
217 when doing case-insensitive key matching. In the future, case-insensitive
218 object key matching may be provided via an option to the generator.
219
220 * easyjson makes use of `unsafe`, which simplifies the code and
221 provides significant performance benefits by allowing no-copy
222 conversion from `[]byte` to `string`. That said, `unsafe` is used
223 only when unmarshaling and parsing JSON, and any `unsafe` operations
224 / memory allocations done will be safely deallocated by
225 easyjson. Set the build tag `easyjson_nounsafe` to compile it
226 without `unsafe`.
227
228 * easyjson is compatible with Google App Engine. The `appengine` build
229 tag (set by App Engine's environment) will automatically disable the
230 use of `unsafe`, which is not allowed in App Engine's Standard
231 Environment. Note that the use with App Engine is still experimental.
232
233 * Floats are formatted using the default precision from Go's `strconv` package.
234 As such, easyjson will not correctly handle high precision floats when
235 marshaling/unmarshaling JSON. Note, however, that there are very few/limited
236 uses where this behavior is not sufficient for general use. That said, a
237 different package may be needed if precise marshaling/unmarshaling of high
238 precision floats to/from JSON is required.
239
240 * While unmarshaling, the JSON parser does the minimal amount of work needed to
241 skip over unmatching parens, and as such full validation is not done for the
242 entire JSON value being unmarshaled/parsed.
243
244 * Currently there is no true streaming support for encoding/decoding as
245 typically for many uses/protocols the final, marshaled length of the JSON
246 needs to be known prior to sending the data. Currently this is not possible
247 with easyjson's architecture.
248
249 * easyjson parser and codegen based on reflection, so it won't work on `package main`
250 files, because they cant be imported by parser.
251
252 ## Benchmarks
253
254 Most benchmarks were done using the example
255 [13kB example JSON](https://dev.twitter.com/rest/reference/get/search/tweets)
256 (9k after eliminating whitespace). This example is similar to real-world data,
257 is well-structured, and contains a healthy variety of different types, making
258 it ideal for JSON serialization benchmarks.
259
260 Note:
261
262 * For small request benchmarks, an 80 byte portion of the above example was
263 used.
264
265 * For large request marshaling benchmarks, a struct containing 50 regular
266 samples was used, making a ~500kB output JSON.
267
268 * Benchmarks are showing the results of easyjson's default behaviour,
269 which makes use of `unsafe`.
270
271 Benchmarks are available in the repository and can be run by invoking `make`.
272
273 ### easyjson vs. encoding/json
274
275 easyjson is roughly 5-6 times faster than the standard `encoding/json` for
276 unmarshaling, and 3-4 times faster for non-concurrent marshaling. Concurrent
277 marshaling is 6-7x faster if marshaling to a writer.
278
279 ### easyjson vs. ffjson
280
281 easyjson uses the same approach for JSON marshaling as
282 [ffjson](https://github.com/pquerna/ffjson), but takes a significantly
283 different approach to lexing and parsing JSON during unmarshaling. This means
284 easyjson is roughly 2-3x faster for unmarshaling and 1.5-2x faster for
285 non-concurrent unmarshaling.
286
287 As of this writing, `ffjson` seems to have issues when used concurrently:
288 specifically, large request pooling hurts `ffjson`'s performance and causes
289 scalability issues. These issues with `ffjson` can likely be fixed, but as of
290 writing remain outstanding/known issues with `ffjson`.
291
292 easyjson and `ffjson` have similar performance for small requests, however
293 easyjson outperforms `ffjson` by roughly 2-5x times for large requests when
294 used with a writer.
295
296 ### easyjson vs. go/codec
297
298 [go/codec](https://github.com/ugorji/go) provides
299 compile-time helpers for JSON generation. In this case, helpers do not work
300 like marshalers as they are encoding-independent.
301
302 easyjson is generally 2x faster than `go/codec` for non-concurrent benchmarks
303 and about 3x faster for concurrent encoding (without marshaling to a writer).
304
305 In an attempt to measure marshaling performance of `go/codec` (as opposed to
306 allocations/memcpy/writer interface invocations), a benchmark was done with
307 resetting length of a byte slice rather than resetting the whole slice to nil.
308 However, the optimization in this exact form may not be applicable in practice,
309 since the memory is not freed between marshaling operations.
310
311 ### easyjson vs 'ujson' python module
312
313 [ujson](https://github.com/esnme/ultrajson) is using C code for parsing, so it
314 is interesting to see how plain golang compares to that. It is important to note
315 that the resulting object for python is slower to access, since the library
316 parses JSON object into dictionaries.
317
318 easyjson is slightly faster for unmarshaling and 2-3x faster than `ujson` for
319 marshaling.
320
321 ### Benchmark Results
322
323 `ffjson` results are from February 4th, 2016, using the latest `ffjson` and go1.6.
324 `go/codec` results are from March 4th, 2016, using the latest `go/codec` and go1.6.
325
326 #### Unmarshaling
327
328 | lib | json size | MB/s | allocs/op | B/op |
329 |:---------|:----------|-----:|----------:|------:|
330 | standard | regular | 22 | 218 | 10229 |
331 | standard | small | 9.7 | 14 | 720 |
332 | | | | | |
333 | easyjson | regular | 125 | 128 | 9794 |
334 | easyjson | small | 67 | 3 | 128 |
335 | | | | | |
336 | ffjson | regular | 66 | 141 | 9985 |
337 | ffjson | small | 17.6 | 10 | 488 |
338 | | | | | |
339 | codec | regular | 55 | 434 | 19299 |
340 | codec | small | 29 | 7 | 336 |
341 | | | | | |
342 | ujson | regular | 103 | N/A | N/A |
343
344 #### Marshaling, one goroutine.
345
346 | lib | json size | MB/s | allocs/op | B/op |
347 |:----------|:----------|-----:|----------:|------:|
348 | standard | regular | 75 | 9 | 23256 |
349 | standard | small | 32 | 3 | 328 |
350 | standard | large | 80 | 17 | 1.2M |
351 | | | | | |
352 | easyjson | regular | 213 | 9 | 10260 |
353 | easyjson* | regular | 263 | 8 | 742 |
354 | easyjson | small | 125 | 1 | 128 |
355 | easyjson | large | 212 | 33 | 490k |
356 | easyjson* | large | 262 | 25 | 2879 |
357 | | | | | |
358 | ffjson | regular | 122 | 153 | 21340 |
359 | ffjson** | regular | 146 | 152 | 4897 |
360 | ffjson | small | 36 | 5 | 384 |
361 | ffjson** | small | 64 | 4 | 128 |
362 | ffjson | large | 134 | 7317 | 818k |
363 | ffjson** | large | 125 | 7320 | 827k |
364 | | | | | |
365 | codec | regular | 80 | 17 | 33601 |
366 | codec*** | regular | 108 | 9 | 1153 |
367 | codec | small | 42 | 3 | 304 |
368 | codec*** | small | 56 | 1 | 48 |
369 | codec | large | 73 | 483 | 2.5M |
370 | codec*** | large | 103 | 451 | 66007 |
371 | | | | | |
372 | ujson | regular | 92 | N/A | N/A |
373
374 \* marshaling to a writer,
375 \*\* using `ffjson.Pool()`,
376 \*\*\* reusing output slice instead of resetting it to nil
377
378 #### Marshaling, concurrent.
379
380 | lib | json size | MB/s | allocs/op | B/op |
381 |:----------|:----------|-----:|----------:|------:|
382 | standard | regular | 252 | 9 | 23257 |
383 | standard | small | 124 | 3 | 328 |
384 | standard | large | 289 | 17 | 1.2M |
385 | | | | | |
386 | easyjson | regular | 792 | 9 | 10597 |
387 | easyjson* | regular | 1748 | 8 | 779 |
388 | easyjson | small | 333 | 1 | 128 |
389 | easyjson | large | 718 | 36 | 548k |
390 | easyjson* | large | 2134 | 25 | 4957 |
391 | | | | | |
392 | ffjson | regular | 301 | 153 | 21629 |
393 | ffjson** | regular | 707 | 152 | 5148 |
394 | ffjson | small | 62 | 5 | 384 |
395 | ffjson** | small | 282 | 4 | 128 |
396 | ffjson | large | 438 | 7330 | 1.0M |
397 | ffjson** | large | 131 | 7319 | 820k |
398 | | | | | |
399 | codec | regular | 183 | 17 | 33603 |
400 | codec*** | regular | 671 | 9 | 1157 |
401 | codec | small | 147 | 3 | 304 |
402 | codec*** | small | 299 | 1 | 48 |
403 | codec | large | 190 | 483 | 2.5M |
404 | codec*** | large | 752 | 451 | 77574 |
405
406 \* marshaling to a writer,
407 \*\* using `ffjson.Pool()`,
408 \*\*\* reusing output slice instead of resetting it to nil