Skip to content

Commit 3130e91

Browse files
authored
Merge pull request #631 from casperisfine/to-json-bench
Encoding benchmark updates
2 parents b95d949 + 5a64fd5 commit 3130e91

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

benchmark/encoder.rb

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
require "benchmark/ips"
22
require "json"
33
require "oj"
4-
require "rapidjson"
4+
5+
Oj.default_options = Oj.default_options.merge(mode: :compat)
56

67
if ENV["ONLY"]
78
RUN = ENV["ONLY"].split(/[,: ]/).map{|x| [x.to_sym, true] }.to_h
@@ -15,12 +16,10 @@
1516

1617
def implementations(ruby_obj)
1718
state = JSON::State.new(JSON.dump_default_options)
18-
1919
{
2020
json_state: ["json (reuse)", proc { state.generate(ruby_obj) }],
2121
json: ["json", proc { JSON.dump(ruby_obj) }],
2222
oj: ["oj", proc { Oj.dump(ruby_obj) }],
23-
rapidjson: ["rapidjson", proc { RapidJSON.dump(ruby_obj) }],
2423
}
2524
end
2625

@@ -38,6 +37,11 @@ def benchmark_encoding(benchmark_name, ruby_obj, check_expected: true, except: [
3837
result = block.call
3938
if check_expected && expected != result
4039
puts "#{name} does not match expected output. Skipping"
40+
puts "Expected:" + '-' * 40
41+
puts expected
42+
puts "Actual:" + '-' * 40
43+
puts result
44+
puts '-' * 40
4145
next
4246
end
4347
rescue => error
@@ -67,12 +71,13 @@ def benchmark_encoding(benchmark_name, ruby_obj, check_expected: true, except: [
6771

6872
# This benchmark spent the overwhelming majority of its time in `ruby_dtoa`. We rely on Ruby's implementation
6973
# which uses a relatively old version of dtoa.c from David M. Gay.
70-
# Oj is noticeably faster here because it limits the precision of floats, breaking roundtriping. That's not
71-
# something we should emulate.
74+
# Oj in `compat` mode is ~10% slower than `json`, but in its default mode is noticeably faster here because
75+
# it limits the precision of floats, breaking roundtriping. That's not something we should emulate.
76+
#
7277
# Since a few years there are now much faster float to string implementations such as Ryu, Dragonbox, etc,
7378
# but all these are implemented in C++11 or newer, making it hard if not impossible to include them.
7479
# Short of a pure C99 implementation of these newer algorithms, there isn't much that can be done to match
7580
# Oj speed without losing precision.
7681
benchmark_encoding "canada.json", JSON.load_file("#{__dir__}/data/canada.json"), check_expected: false, except: %i(json_state)
7782

78-
benchmark_encoding "many #to_json calls", [{Object.new => Object.new, 12 => 54.3, Integer => Float, Time.now => Date.today}] * 20, except: %i(json_state)
83+
benchmark_encoding "many #to_json calls", [{object: Object.new, int: 12, float: 54.3, class: Float, time: Time.now, date: Date.today}] * 20, except: %i(json_state)

0 commit comments

Comments
 (0)