oj 2.18.5 → 3.16.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. checksums.yaml +5 -5
  2. data/CHANGELOG.md +1452 -0
  3. data/README.md +53 -221
  4. data/RELEASE_NOTES.md +61 -0
  5. data/ext/oj/buf.h +54 -72
  6. data/ext/oj/cache.c +329 -0
  7. data/ext/oj/cache.h +22 -0
  8. data/ext/oj/cache8.c +61 -63
  9. data/ext/oj/cache8.h +12 -39
  10. data/ext/oj/circarray.c +38 -67
  11. data/ext/oj/circarray.h +16 -42
  12. data/ext/oj/code.c +214 -0
  13. data/ext/oj/code.h +40 -0
  14. data/ext/oj/compat.c +194 -110
  15. data/ext/oj/custom.c +1074 -0
  16. data/ext/oj/debug.c +126 -0
  17. data/ext/oj/dump.c +1276 -2494
  18. data/ext/oj/dump.h +110 -0
  19. data/ext/oj/dump_compat.c +897 -0
  20. data/ext/oj/dump_leaf.c +162 -0
  21. data/ext/oj/dump_object.c +710 -0
  22. data/ext/oj/dump_strict.c +399 -0
  23. data/ext/oj/encode.h +7 -42
  24. data/ext/oj/encoder.c +43 -0
  25. data/ext/oj/err.c +28 -53
  26. data/ext/oj/err.h +49 -46
  27. data/ext/oj/extconf.rb +33 -32
  28. data/ext/oj/fast.c +1082 -1098
  29. data/ext/oj/intern.c +313 -0
  30. data/ext/oj/intern.h +22 -0
  31. data/ext/oj/mem.c +318 -0
  32. data/ext/oj/mem.h +53 -0
  33. data/ext/oj/mimic_json.c +919 -0
  34. data/ext/oj/object.c +545 -625
  35. data/ext/oj/odd.c +158 -168
  36. data/ext/oj/odd.h +32 -58
  37. data/ext/oj/oj.c +1727 -2080
  38. data/ext/oj/oj.h +334 -259
  39. data/ext/oj/parse.c +974 -753
  40. data/ext/oj/parse.h +97 -90
  41. data/ext/oj/parser.c +1600 -0
  42. data/ext/oj/parser.h +103 -0
  43. data/ext/oj/rails.c +1478 -0
  44. data/ext/oj/rails.h +18 -0
  45. data/ext/oj/reader.c +136 -163
  46. data/ext/oj/reader.h +76 -112
  47. data/ext/oj/resolve.c +45 -94
  48. data/ext/oj/resolve.h +7 -34
  49. data/ext/oj/rxclass.c +144 -0
  50. data/ext/oj/rxclass.h +26 -0
  51. data/ext/oj/saj.c +445 -511
  52. data/ext/oj/saj2.c +584 -0
  53. data/ext/oj/saj2.h +23 -0
  54. data/ext/oj/scp.c +82 -143
  55. data/ext/oj/simd.h +10 -0
  56. data/ext/oj/sparse.c +749 -644
  57. data/ext/oj/stream_writer.c +329 -0
  58. data/ext/oj/strict.c +114 -112
  59. data/ext/oj/string_writer.c +517 -0
  60. data/ext/oj/trace.c +72 -0
  61. data/ext/oj/trace.h +55 -0
  62. data/ext/oj/usual.c +1218 -0
  63. data/ext/oj/usual.h +69 -0
  64. data/ext/oj/util.c +136 -0
  65. data/ext/oj/util.h +20 -0
  66. data/ext/oj/val_stack.c +75 -72
  67. data/ext/oj/val_stack.h +94 -127
  68. data/ext/oj/validate.c +46 -0
  69. data/ext/oj/wab.c +586 -0
  70. data/lib/oj/active_support_helper.rb +1 -3
  71. data/lib/oj/bag.rb +8 -1
  72. data/lib/oj/easy_hash.rb +21 -13
  73. data/lib/oj/error.rb +10 -12
  74. data/lib/oj/json.rb +188 -0
  75. data/lib/oj/mimic.rb +165 -26
  76. data/lib/oj/saj.rb +20 -6
  77. data/lib/oj/schandler.rb +5 -4
  78. data/lib/oj/state.rb +135 -0
  79. data/lib/oj/version.rb +2 -3
  80. data/lib/oj.rb +3 -31
  81. data/pages/Advanced.md +22 -0
  82. data/pages/Compatibility.md +25 -0
  83. data/pages/Custom.md +23 -0
  84. data/pages/Encoding.md +65 -0
  85. data/pages/InstallOptions.md +20 -0
  86. data/pages/JsonGem.md +94 -0
  87. data/pages/Modes.md +161 -0
  88. data/pages/Options.md +337 -0
  89. data/pages/Parser.md +309 -0
  90. data/pages/Rails.md +167 -0
  91. data/pages/Security.md +20 -0
  92. data/pages/WAB.md +13 -0
  93. metadata +126 -163
  94. data/ext/oj/hash.c +0 -163
  95. data/ext/oj/hash.h +0 -46
  96. data/ext/oj/hash_test.c +0 -512
  97. data/test/_test_active.rb +0 -76
  98. data/test/_test_active_mimic.rb +0 -96
  99. data/test/_test_mimic_rails.rb +0 -126
  100. data/test/activesupport_datetime_test.rb +0 -23
  101. data/test/bug.rb +0 -51
  102. data/test/bug2.rb +0 -10
  103. data/test/bug3.rb +0 -46
  104. data/test/bug_fast.rb +0 -32
  105. data/test/bug_load.rb +0 -24
  106. data/test/crash.rb +0 -111
  107. data/test/curl/curl_oj.rb +0 -46
  108. data/test/curl/get_oj.rb +0 -24
  109. data/test/curl/just_curl.rb +0 -31
  110. data/test/curl/just_oj.rb +0 -51
  111. data/test/example.rb +0 -11
  112. data/test/files.rb +0 -29
  113. data/test/foo.rb +0 -24
  114. data/test/helper.rb +0 -27
  115. data/test/io.rb +0 -48
  116. data/test/isolated/shared.rb +0 -310
  117. data/test/isolated/test_mimic_after.rb +0 -13
  118. data/test/isolated/test_mimic_alone.rb +0 -12
  119. data/test/isolated/test_mimic_as_json.rb +0 -45
  120. data/test/isolated/test_mimic_before.rb +0 -13
  121. data/test/isolated/test_mimic_define.rb +0 -28
  122. data/test/isolated/test_mimic_rails_after.rb +0 -22
  123. data/test/isolated/test_mimic_rails_before.rb +0 -21
  124. data/test/isolated/test_mimic_rails_datetime.rb +0 -27
  125. data/test/isolated/test_mimic_redefine.rb +0 -15
  126. data/test/mod.rb +0 -16
  127. data/test/perf.rb +0 -107
  128. data/test/perf_compat.rb +0 -128
  129. data/test/perf_fast.rb +0 -164
  130. data/test/perf_file.rb +0 -64
  131. data/test/perf_object.rb +0 -138
  132. data/test/perf_saj.rb +0 -109
  133. data/test/perf_scp.rb +0 -151
  134. data/test/perf_simple.rb +0 -287
  135. data/test/perf_strict.rb +0 -128
  136. data/test/rails.rb +0 -50
  137. data/test/russian.rb +0 -18
  138. data/test/sample/change.rb +0 -14
  139. data/test/sample/dir.rb +0 -19
  140. data/test/sample/doc.rb +0 -36
  141. data/test/sample/file.rb +0 -48
  142. data/test/sample/group.rb +0 -16
  143. data/test/sample/hasprops.rb +0 -16
  144. data/test/sample/layer.rb +0 -12
  145. data/test/sample/line.rb +0 -20
  146. data/test/sample/oval.rb +0 -10
  147. data/test/sample/rect.rb +0 -10
  148. data/test/sample/shape.rb +0 -35
  149. data/test/sample/text.rb +0 -20
  150. data/test/sample.rb +0 -55
  151. data/test/sample_json.rb +0 -37
  152. data/test/struct.rb +0 -29
  153. data/test/test_compat.rb +0 -398
  154. data/test/test_debian.rb +0 -53
  155. data/test/test_fast.rb +0 -458
  156. data/test/test_file.rb +0 -245
  157. data/test/test_gc.rb +0 -49
  158. data/test/test_hash.rb +0 -29
  159. data/test/test_object.rb +0 -745
  160. data/test/test_saj.rb +0 -186
  161. data/test/test_scp.rb +0 -396
  162. data/test/test_serializer.rb +0 -59
  163. data/test/test_strict.rb +0 -254
  164. data/test/test_various.rb +0 -1383
  165. data/test/test_writer.rb +0 -308
  166. data/test/write_timebars.rb +0 -31
data/pages/Options.md ADDED
@@ -0,0 +1,337 @@
1
+ # Oj Options
2
+
3
+ To change default serialization mode use the following form. Attempting to
4
+ modify the Oj.default_options Hash directly will not set the changes on the
5
+ actual default options but on a copy of the Hash:
6
+
7
+ ```ruby
8
+ Oj.default_options = {:mode => :compat }
9
+ ```
10
+
11
+ Another way to make use of options when calling load or dump methods is to
12
+ pass in a Hash with the options already set in the Hash. This is slightly less
13
+ efficient than setting the globals for many smaller JSON documents but does
14
+ provide a more thread safe approach to using custom options for loading and
15
+ dumping.
16
+
17
+ ### Options for serializer and parser
18
+
19
+ ### :allow_blank [Boolean]
20
+
21
+ If true a nil input to load will return nil and not raise an Exception.
22
+
23
+ ### :allow_gc [Boolean]
24
+
25
+ Allow or prohibit GC during parsing, default is true (allow).
26
+
27
+ ### :allow_invalid_unicode [Boolean]
28
+
29
+ Allow invalid unicode, default is false (don't allow).
30
+
31
+ ### :allow_nan
32
+
33
+ Alias for the :nan option.
34
+
35
+ ### :array_class [Class]
36
+
37
+ Class to use instead of Array on load.
38
+
39
+ ### :array_nl
40
+
41
+ Trailer appended to the end of an array dump. The default is an empty
42
+ string. Primarily intended for json gem compatibility. Using just indent as an
43
+ integer gives better performance.
44
+
45
+ ### :ascii_only
46
+
47
+ If true all non-ASCII character are escaped when dumping. This is the same as
48
+ setting the :escape_mode options to :ascii and exists for json gem
49
+ compatibility.
50
+
51
+ ### :auto_define [Boolean]
52
+
53
+ Automatically define classes if they do not exist.
54
+
55
+ ### :bigdecimal_as_decimal [Boolean]
56
+
57
+ If true dump BigDecimal as a decimal number otherwise as a String
58
+
59
+ ### :bigdecimal_load [Symbol]
60
+
61
+ Determines how to load decimals.
62
+
63
+ - `:bigdecimal` convert all decimal numbers to BigDecimal.
64
+
65
+ - `:float` convert all decimal numbers to Float.
66
+
67
+ - `:auto` the most precise for the number of digits is used.
68
+
69
+ - `:fast` faster conversion to Float.
70
+
71
+ - `:ruby` convert to Float using the Ruby `to_f` conversion.
72
+
73
+ This can also be set with `:decimal_class` when used as a load or
74
+ parse option to match the JSON gem. In that case either `Float`,
75
+ `BigDecimal`, or `nil` can be provided.
76
+
77
+ ### :cache_keys [Boolean]
78
+
79
+ If true Hash keys are cached or interned. There are trade-offs with
80
+ caching keys. Large caches will use more memory and in extreme cases
81
+ (like over a million) the cache may be slower than not using
82
+ it. Repeated parsing of similar JSON docs is where cache_keys shines
83
+ especially with symbol keys.
84
+
85
+ There is a maximum length for cached keys. Any key longer than 34
86
+ bytes is not cached. Everything still works but the key is not cached.
87
+
88
+ ### :cache_strings [Int]
89
+
90
+ Shorter strings can be cached for better performance. A limit,
91
+ cache_strings, defines the upper limit on what strings are cached. As
92
+ with cached keys only strings less than 35 bytes are cached even if
93
+ the limit is set higher. Setting the limit to zero effectively
94
+ disables the caching of string values.
95
+
96
+ Note that caching for strings is for string values and not Hash keys
97
+ or Object attributes.
98
+
99
+ ### :circular [Boolean]
100
+
101
+ Detect circular references while dumping. In :compat mode raise a
102
+ NestingError. For other modes except the :object mode place a null in the
103
+ output. For :object mode place references in the output that will be used to
104
+ recreate the looped references on load.
105
+
106
+ ### :class_cache [Boolean]
107
+
108
+ Cache classes for faster parsing. This option should not be used if
109
+ dynamically modifying classes or reloading classes then don't use this.
110
+
111
+ ### :compat_bigdecimal [Boolean]
112
+
113
+ Determines how to load decimals when in `:compat` mode.
114
+
115
+ - `true` convert all decimal numbers to BigDecimal.
116
+
117
+ - `false` convert all decimal numbers to Float.
118
+
119
+ ### :create_additions
120
+
121
+ A flag indicating that the :create_id key, when encountered during parsing,
122
+ should create an Object matching the class name specified in the value
123
+ associated with the key.
124
+
125
+ ### :create_id [String]
126
+
127
+ The :create_id option specifies that key is used for dumping and loading when
128
+ specifying the class for an encoded object. The default is `json_create`.
129
+
130
+ In the `:custom` mode, setting the `:create_id` to nil will cause Complex,
131
+ Rational, Range, and Regexp to be output as strings instead of as JSON
132
+ objects.
133
+
134
+ ### :empty_string [Boolean]
135
+
136
+ If true an empty or all whitespace input will not raise an Exception. The
137
+ default_options will be honored for :null, :strict, and :custom modes. Ignored
138
+ for :custom and :wab. The :compat has a more complex set of rules. The JSON
139
+ gem compatibility is best described by examples.
140
+
141
+ ```
142
+ JSON.parse('') => raise
143
+ JSON.parse(' ') => raise
144
+ JSON.load('') => nil
145
+ JSON.load('', nil, allow_blank: false) => raise
146
+ JSON.load('', nil, allow_blank: true) => nil
147
+ JSON.load(' ') => raise
148
+ JSON.load(' ', nil, allow_blank: false) => raise
149
+ JSON.load(' ', nil, allow_blank: true) => raise
150
+ ```
151
+
152
+ ### :escape_mode [Symbol]
153
+
154
+ Determines the characters to escape when dumping. Only the :ascii and
155
+ :json modes are supported in :compat mode.
156
+
157
+ - `:newline` allows unescaped newlines in the output.
158
+
159
+ - `:json` follows the JSON specification. This is the default mode.
160
+
161
+ - `:slash` escapes `/` characters.
162
+
163
+ - `:xss_safe` escapes HTML and XML characters such as `&` and `<`.
164
+
165
+ - `:ascii` escapes all non-ascii or characters with the hi-bit set.
166
+
167
+ - `:unicode_xss` escapes a special unicodes and is xss safe.
168
+
169
+ ### :float_precision [Fixnum]
170
+
171
+ The number of digits of precision when dumping floats, 0 indicates use Ruby directly.
172
+
173
+ ### :hash_class [Class]
174
+
175
+ Class to use instead of Hash on load. This is the same as the :object_class.
176
+
177
+ ### :ignore [Array]
178
+
179
+ Ignore all the classes in the Array when dumping. A value of nil indicates
180
+ ignore nothing.
181
+
182
+ ### :indent [Fixnum]
183
+
184
+ Number of spaces to indent each element in a JSON document, zero is no newline
185
+ between JSON elements, negative indicates no newline between top level JSON
186
+ elements in a stream.
187
+
188
+ ### :indent_str
189
+
190
+ Indentation for each element when dumping. The default is an empty
191
+ string. Primarily intended for json gem compatibility. Using just indent as an
192
+ integer gives better performance.
193
+
194
+ ### :integer_range [Range]
195
+
196
+ Dump integers outside range as strings.
197
+ Note: range bounds must be Fixnum.
198
+
199
+ ### :match_string
200
+
201
+ Provides a means to detect strings that should be used to create non-String
202
+ objects. The value to the option must be a Hash with keys that are regular
203
+ expressions and values are class names. For strict json gem compatibility a
204
+ RegExp should be used. For better performance but sacrificing some regexp
205
+ options a string can be used and the C version of regex will be used instead.
206
+
207
+ ### :max_nesting
208
+
209
+ The maximum nesting depth on both dump and load that is allowed. This exists
210
+ for json gem compatibility.
211
+
212
+ ### :mode [Symbol]
213
+
214
+ Primary behavior for loading and dumping. The :mode option controls which
215
+ other options are in effect. For more details see the {file:Modes.md} page. By
216
+ default Oj uses the :custom mode which is provides the highest degree of
217
+ customization.
218
+
219
+ ### :nan [Symbol]
220
+
221
+ How to dump Infinity, -Infinity, and NaN in :null, :strict, and :compat
222
+ mode. Default is :auto but is ignored in the :compat and :rails modes.
223
+
224
+ - `:null` places a null
225
+
226
+ - `:huge` places a huge number
227
+
228
+ - `:word` places Infinity or NaN
229
+
230
+ - `:raise` raises and exception
231
+
232
+ - `:auto` uses default for each mode which are `:raise` for `:strict`, `:null` for `:null`, and `:word` for `:compat`.
233
+
234
+ ### :nilnil [Boolean]
235
+
236
+ If true a nil input to load will return nil and not raise an Exception.
237
+
238
+ ### :object_class
239
+
240
+ The class to use when creating a Hash on load instead of the Hash class.
241
+
242
+ ### :object_nl
243
+
244
+ Trailer appended to the end of an object dump. The default is an empty
245
+ string. Primarily intended for json gem compatibility. Using just indent as an
246
+ integer gives better performance.
247
+
248
+ ### :omit_nil [Boolean]
249
+
250
+ If true, Hash and Object attributes with nil values are omitted.
251
+
252
+ ### :quirks_mode [Boolean]
253
+
254
+ Allow single JSON values instead of documents, default is true (allow). This
255
+ can also be used in :compat mode to be backward compatible with older versions
256
+ of the json gem.
257
+
258
+ ### :safe
259
+
260
+ The JSON gem includes the complete JSON in parse errors with no limit
261
+ on size. To break from the JSON gem behavior for this case set `:safe`
262
+ to true.
263
+
264
+ ### :second_precision [Fixnum]
265
+
266
+ The number of digits after the decimal when dumping the seconds of time.
267
+
268
+ ### :skip_null_byte [Boolean]
269
+
270
+ If true, null bytes in strings will be omitted when dumping.
271
+
272
+ ### :space
273
+
274
+ String inserted after the ':' character when dumping a JSON object. The
275
+ default is an empty string. Primarily intended for json gem
276
+ compatibility. Using just indent as an integer gives better performance.
277
+
278
+ ### :space_before
279
+
280
+ String inserted before the ':' character when dumping a JSON object. The
281
+ default is an empty string. Primarily intended for json gem
282
+ compatibility. Using just indent as an integer gives better performance.
283
+
284
+ ### :symbol_keys [Boolean]
285
+
286
+ Use symbols instead of strings for hash keys.
287
+
288
+ ### :symbolize_names [Boolean]
289
+
290
+ Like :symbol_keys has keys are made into symbols but only when
291
+ mimicking the JSON gem and then only as the JSON gem honors it so
292
+ JSON.parse honors the option but JSON.load does not.
293
+
294
+ ### :trace
295
+
296
+ When true dump and load functions are traced by printing beginning and ending
297
+ of blocks and of specific calls.
298
+
299
+ ### :time_format [Symbol]
300
+
301
+ The :time_format when dumping.
302
+
303
+ - `:unix` time is output as a decimal number in seconds since epoch including fractions of a second.
304
+
305
+ - `:unix_zone` is similar to the `:unix` format but with the timezone encoded in
306
+ the exponent of the decimal number of seconds since epoch.
307
+
308
+ - `:xmlschema` time is output as a string that follows the XML schema definition.
309
+
310
+ - `:ruby` time is output as a string formatted using the Ruby `to_s` conversion.
311
+
312
+ ### :use_as_json [Boolean]
313
+
314
+ Call `as_json()` methods on dump, default is false. The option is ignored in
315
+ the :compat and :rails modes.
316
+
317
+
318
+ ### :use_raw_json [Boolean]
319
+
320
+ Call `raw_json()` methods on dump, default is false. The option is
321
+ accepted in the :compat and :rails modes even though it is not
322
+ supported by other JSON gems. It provides a means to optimize dump or
323
+ generate performance. The `raw_json(depth, indent)` method should be
324
+ called only by Oj. It is not intended for any other use. This is meant
325
+ to replace the abused `to_json` methods. Calling `Oj.dump` inside the
326
+ `raw_json` with the object itself when `:use_raw_json` is true will
327
+ result in an infinite loop.
328
+
329
+ ### :use_to_hash [Boolean]
330
+
331
+ Call `to_hash()` methods on dump, default is false. The option is ignored in
332
+ the :compat and :rails modes.
333
+
334
+ ### :use_to_json [Boolean]
335
+
336
+ Call `to_json()` methods on dump, default is false. The option is ignored in
337
+ the :compat and :rails modes.
data/pages/Parser.md ADDED
@@ -0,0 +1,309 @@
1
+ # How Oj Just Got Faster
2
+
3
+ The original Oj parser is a performant parser that supports several
4
+ modes. As of this writing Oj is almost 10 years old. A dinosaur by
5
+ coding standards. It was time for an upgrade. Dealing with issues over
6
+ the years it became clear that a few things could have been done
7
+ better. The new `Oj::Parser` is a response that not only attempts to
8
+ address some of the issues but also give the Oj parser a significant
9
+ boost in performance. `Oj::Parser` takes a different approach to JSON
10
+ parsing than the now legacy Oj parser. Not really a legacy parser yet
11
+ since the `Oj::Parser` is not a drop-in replacement for the JSON gem
12
+ but it is as much 3 times or more faster than the previous parser in
13
+ some modes.
14
+
15
+ ## Address Issues
16
+
17
+ There are a few features of the`Oj.load` parser that continue to be
18
+ the reason for many of the issue on the project. The most significant
19
+ area is compatibility with both Rails and the JSON gem as they battle
20
+ it out for which behavior will win out in any particular
21
+ situation. Most of the issues are on the writing or dumping side of
22
+ the JSON packages but some are present on the parsing as
23
+ well. Conversion of decimals is one area where the Rails and the JSON
24
+ gem vary. The `Oj::Parser` addresses this by allowing for completely
25
+ separate parser instances. Create a parser and configure it for the
26
+ situation and leave the others parsers on their own.
27
+
28
+ The `Oj::Parser` is mostly compatible with the JSON gem and Rails but
29
+ no claims are made that the behavior will be the same as either.
30
+
31
+ The most frequent issues that can addressed with the new parser are
32
+ around the handling of options. For `Oj.load` there is a set of
33
+ default options that can be set and the same options can be specified
34
+ for each call to parse or load. This approach as a couple of
35
+ downsides. One the defaults are shared across all calls to parse no
36
+ matter what the desire mode is. The second is that having to provide
37
+ all the options on each parse call incurs a performance penalty and is
38
+ just annoying to repeat the same set of options over may calls.
39
+
40
+ By localizing options to a specific parser instance there is never any
41
+ bleed over to other instances.
42
+
43
+ ## How
44
+
45
+ It's wonderful to wish for a faster parser that solves all the
46
+ annoyances of the previous parser but how was it done is a much more
47
+ interesting question to answer.
48
+
49
+ At the core, the API for parsing was changed. Instead of a sinle
50
+ global parser any number of parsers can be created and each is separate
51
+ from the others. The parser itself is able to rip through a JSON
52
+ string, stream, or file and then make calls to a delegate to process
53
+ the JSON elements according to the delegate behavior. This is similar
54
+ to the `Oj.load` parser but the new parser takes advantage of
55
+ character maps, reduced conditional branching, and calling function
56
+ pointers.
57
+
58
+ ### Options
59
+
60
+ As mentioned, one way to change the options issues was to change the
61
+ API. Instead of having a shared set of default options a separate
62
+ parser is created and configured for each use case. Options are set
63
+ with methods on the parser so no more guessing what options are
64
+ available. With options isolated to individual parsers there is no
65
+ unintended leakage to other parse use cases.
66
+
67
+ ### Structure
68
+
69
+ A relative small amount of time is spent in the actual parsing of JSON
70
+ in `Oj.load`. Most of the time is spent building the Ruby
71
+ Objects. Even cutting the parsing time in half only gives a 10%
72
+ improvement in performance but 10% is still an improvement.
73
+
74
+ The `Oj::Parser` is designed to reduce conditional branching. To do
75
+ that it uses character maps for the various states that the parser
76
+ goes through when parsing. There is no recursion as the JSON elements
77
+ are parsed. The use of a character maps for each parser state means
78
+ the parser function can and is re-entrant so partial blocks of JSON
79
+ can be parsed and the results combined.
80
+
81
+ There are no Ruby calls in the parser itself. Instead delegates are
82
+ used to implement the various behaviors of the parser which are
83
+ currently validation (validate), callbacks (SAJ), or building Ruby
84
+ objects (usual). The delegates are where all the Ruby calls and
85
+ related optimizations take place.
86
+
87
+ Considering JSON file parsing, `Oj.load_file` is able to read a file a
88
+ block at a time and the new `Oj::Parser` does the same. There was a
89
+ change in how that is done though. `Oj.load_file` sets up a reader
90
+ that must be called for each character. Basically a buffered
91
+ reader. `Oj::Parser` drops down a level and uses a re-entrant parser
92
+ that takes a block of bytes at a time so there is no call needed for
93
+ each character but rather just iterating over the block read from the
94
+ file.
95
+
96
+ Reading a block at a time also allows for an efficient second thread
97
+ to be used for reading blocks. That feature is not in the first
98
+ iteration of the `Oj::Parser` but the stage is set for it in the
99
+ future. The same approach was used successfully in
100
+ [OjC](https://github.com/ohler55/ojc) which is where the code for the
101
+ parser was taken from.
102
+
103
+ ### Delegates
104
+
105
+ There are three delegates; validate, SAJ, and usual.
106
+
107
+ #### Validate
108
+
109
+ The validate delegate is trivial in that does nothing other than let
110
+ the parser complete. There are no options for the validate
111
+ delegate. By not making any Ruby calls other than to start the parsing
112
+ the validate delegate is no surprise that the validate delegate is the
113
+ best performer.
114
+
115
+ #### SAJ (Simple API for JSON)
116
+
117
+ The SAJ delegate is compatible with the SAJ handlers used with
118
+ `Oj.saj_parse` so it needs to keep track of keys for the
119
+ callbacks. Two optimizations are used. The first is a reuseable key
120
+ stack while the second is a string cache similar to the Ruby intern
121
+ function.
122
+
123
+ When parsing a Hash (JSON object) element the key is passed to the
124
+ callback function if the SAJ handler responds to the method. The key
125
+ is also provided when closing an Array or Hash that is part of a
126
+ parent Hash. A key stack supports this.
127
+
128
+ If the option is turned on a lookup is made and previously cached key
129
+ VALUEs are used. This avoids creating the string for the key and
130
+ setting the encoding on it. The cache used is a auto expanding hash
131
+ implementation that is limited to strings less than 35 characters
132
+ which covers most keys. Larger strings use the slower string creation
133
+ approach. The use of the cache reduces object creation which save on
134
+ both memory allocation and time. It is not appropriate for one time
135
+ parsing of say all the keys in a dictionary but is ideally suited for
136
+ loading similar JSON multiple times.
137
+
138
+ #### Usual
139
+
140
+ By far the more complex of the delegates is the 'usual' delegate. The
141
+ usual delegate builds Ruby Objects when parsing JSON. It incorporates
142
+ many options for configuration and makes use of a number of
143
+ optimizations.
144
+
145
+ ##### Reduce Branching
146
+
147
+ In keeping with the goal of reducing conditional branching most of the
148
+ delegate options are implemented by changing a function pointer
149
+ according to the option selected. For example when turning on or off
150
+ `:symbol_keys` the function to calculate the key is changed so no
151
+ decision needs to be made during parsing. Using this approach option
152
+ branching happens when the option is set and not each time when
153
+ parsing.
154
+
155
+ ##### Cache
156
+
157
+ Creating Ruby Objects whether Strings, Array, or some other class is
158
+ expensive. Well expensive when running at the speeds Oj runs at. One
159
+ way to reduce Object creation is to cache those objects on the
160
+ assumption that they will most likely be used again. This is
161
+ especially true of Hash keys and Object attribute IDs. When creating
162
+ Objects from a class name in the JSON a class cache saves resolving
163
+ the string to a class each time. Of course there are times when
164
+ caching is not preferred so caching can be turned on or off with
165
+ option methods on the parser which are passed down to the delegate..
166
+
167
+ The Oj cache implementation is an auto expanding hash. When certain
168
+ limits are reached the hash is expanded and rehashed. Rehashing can
169
+ take some time as the number of items cached increases so there is
170
+ also an option to start with a larger cache size to avoid or reduce
171
+ the likelihood of a rehash.
172
+
173
+ The Oj cache has an advantage over the Ruby intern function
174
+ (`rb_intern()`) in that several steps are needed for some cached
175
+ items. As an example Object attribute IDs are created by adding an `@`
176
+ character prefix to a string and then converting to a ID. This is done
177
+ once when inserting into the cache and after that only a lookup is
178
+ needed.
179
+
180
+ ##### Bulk Insert
181
+
182
+ The Ruby functions available for C extension functions are extensive
183
+ and offer many options across the board. The bulk insert functions for
184
+ both Arrays and Hashes are much faster than appending or setting
185
+ functions that set one value at a time. The Array bulk insert is
186
+ around 15 times faster and for Hash it is about 3 times faster.
187
+
188
+ To take advantage of the bulk inserts arrays of VALUEs are
189
+ needed. With a little planning there VALUE arrays can be reused which
190
+ leads into another optimization, the use of stacks.
191
+
192
+ ##### Stacks
193
+
194
+ Parsing requires memory to keep track of values when parsing nested
195
+ JSON elements. That can be done on the call stack making use of
196
+ recursive calls or it can be done with a stack managed by the
197
+ parser. The `Oj.load` method maintains a stack for Ruby object and
198
+ builds the output as the parsing progresses.
199
+
200
+ `Oj::Parser` uses three different stacks. One stack for values, one
201
+ for keys, and one for collections (Array and Hash). By postponing the
202
+ creation of the collection elements the bulk insertions for Array and
203
+ Hash can be used. For arrays the use of a value stack and creating the
204
+ array after all elements have been identified gives a 15x improvement
205
+ in array creation.
206
+
207
+ For Hash the story is a little different. The bulk insert for Hash
208
+ alternates keys and values but there is a wrinkle to consider. Since
209
+ Ruby Object creation is triggered by the occurrence of an element that
210
+ matches a creation identifier the creation of a collection is not just
211
+ for Array and Hash but also Object. Setting Object attributes uses an
212
+ ID and not a VALUE. For that reason the keys should not be created as
213
+ String or Symbol types as they would be ignored and the VALUE creation
214
+ wasted when setting Object attributes. Using the bulk insert for Hash
215
+ gives a 3x improvement for that part of the object building.
216
+
217
+ Looking at the Object creation the JSON gem expects a class method of
218
+ `#json_create(arg)`. The single argument is the Hash resulting from
219
+ the parsing assuming that the parser parsed to a Hash first. This is
220
+ less than ideal from a performance perspective so `Oj::Parser`
221
+ provides an option to take that approach or to use the much more
222
+ efficient approach of never creating the Hash but instead creating the
223
+ Object and then setting the attributes directly.
224
+
225
+ To further improve performance and reduce the amount of memory
226
+ allocations and frees the stacks are reused from one call to `#parse`
227
+ to another.
228
+
229
+ ## Results
230
+
231
+ The results are even better than expected. Running the
232
+ [perf_parser.rb](https://github.com/ohler55/oj/blob/develop/test/perf_parser.rb)
233
+ file shows the improvements. There are four comparisons all run on a
234
+ MacBook Pro with Intel processor.
235
+
236
+ ### Validation
237
+
238
+ Without a comparible parser that just validates a JSON document the
239
+ `Oj.saj_parse` callback parser with a nil handler is used for
240
+ comparison to the new `Oj::Parser.new(:validate)`. In that case the
241
+ comparison is:
242
+
243
+ ```
244
+ System time (secs) rate (ops/sec)
245
+ ------------------- ----------- --------------
246
+ Oj::Parser.validate 0.101 494369.136
247
+ Oj::Saj.none 0.205 244122.745
248
+ ```
249
+
250
+ The `Oj::Parser.new(:validate)` is **2.03** times faster!
251
+
252
+ ### Callback
253
+
254
+ Oj has two callback parsers. One is SCP and the other SAJ. Both are
255
+ similar in that a handler is provided that implements methods for
256
+ processing the various element types in a JSON document. Comparing
257
+ `Oj.saj_parse` to `Oj::Parser.new(:saj)` with a all callback methods
258
+ implemented handler gives the following raw results:
259
+
260
+ ```
261
+ System time (secs) rate (ops/sec)
262
+ -------------- ----------- --------------
263
+ Oj::Parser.saj 0.783 63836.986
264
+ Oj::Saj.all 1.182 42315.397
265
+ ```
266
+
267
+ The `Oj::Parser.new(:saj)` is **1.51** times faster.
268
+
269
+ ### Parse to Ruby primitives
270
+
271
+ Parsing to Ruby primitives and Array and Hash is possible with most
272
+ parsers including the JSON gem parser. The raw results comparing
273
+ `Oj.strict_load`, `Oj::Parser.new(:usual)`, and the JSON gem are:
274
+
275
+ ```
276
+ System time (secs) rate (ops/sec)
277
+ ---------------- ----------- --------------
278
+ Oj::Parser.usual 0.452 110544.876
279
+ Oj::strict_load 0.699 71490.257
280
+ JSON::Ext 1.009 49555.094
281
+ ```
282
+
283
+ The `Oj::Parser.new(:saj)` is **1.55** times faster than `Oj.load` and
284
+ **2.23** times faster than the JSON gem.
285
+
286
+ ### Object
287
+
288
+ Oj supports two modes for Object serialization and
289
+ deserialization. Comparing to the JSON gem compatible mode
290
+ `Oj.compat_load`, `Oj::Parser.new(:usual)`, and the JSON gem yields
291
+ the following raw results:
292
+
293
+ ```
294
+ System time (secs) rate (ops/sec)
295
+ ---------------- ----------- --------------
296
+ Oj::Parser.usual 0.071 703502.033
297
+ Oj::compat_load 0.225 221762.927
298
+ JSON::Ext 0.401 124638.859
299
+ ```
300
+
301
+ The `Oj::Parser.new(:saj)` is **3.17** times faster than
302
+ `Oj.compat_load` and **5.64** times faster than the JSON gem.
303
+
304
+ ## Summary
305
+
306
+ With a performance boost of from 1.5x to over 3x over the `Oj.load`
307
+ parser the new `Oj::Parser` is a big win in the performance arena. The
308
+ isolation of options is another feature that should make life easier
309
+ for developers.