From 01f0bc907333d4a5c51db0a82f9c671b110e6493 Mon Sep 17 00:00:00 2001 From: Jean Boussier Date: Wed, 29 Jan 2025 11:42:51 +0100 Subject: [PATCH] Make benchmarks JRuby compatible Co-Authored-By: Charles Oliver Nutter --- benchmark/encoder.rb | 17 ++++++++++++----- benchmark/parser.rb | 24 +++++++++++++++++++----- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/benchmark/encoder.rb b/benchmark/encoder.rb index 92464cea..f0a05dbd 100644 --- a/benchmark/encoder.rb +++ b/benchmark/encoder.rb @@ -1,9 +1,11 @@ require "benchmark/ips" require "json" require "date" -require "oj" - -Oj.default_options = Oj.default_options.merge(mode: :compat) +begin + require "oj" + Oj.default_options = Oj.default_options.merge(mode: :compat) +rescue LoadError +end if ENV["ONLY"] RUN = ENV["ONLY"].split(/[,: ]/).map{|x| [x.to_sym, true] }.to_h @@ -18,11 +20,16 @@ def implementations(ruby_obj) state = JSON::State.new(JSON.dump_default_options) coder = JSON::Coder.new - { + implementations = { json: ["json", proc { JSON.generate(ruby_obj) }], json_coder: ["json_coder", proc { coder.dump(ruby_obj) }], - oj: ["oj", proc { Oj.dump(ruby_obj) }], } + + if defined?(Oj) + implementations[:oj] = ["oj", proc { Oj.dump(ruby_obj) }] + end + + implementations end def benchmark_encoding(benchmark_name, ruby_obj, check_expected: true, except: []) diff --git a/benchmark/parser.rb b/benchmark/parser.rb index 8bf30c0f..a2bd17ef 100644 --- a/benchmark/parser.rb +++ b/benchmark/parser.rb @@ -1,7 +1,14 @@ require "benchmark/ips" require "json" -require "oj" -require "rapidjson" +begin + require "oj" +rescue LoadError +end + +begin + require "rapidjson" +rescue LoadError +end if ENV["ONLY"] RUN = ENV["ONLY"].split(/[,: ]/).map{|x| [x.to_sym, true] }.to_h @@ -20,9 +27,16 @@ def benchmark_parsing(name, json_output) Benchmark.ips do |x| x.report("json") { JSON.parse(json_output) } if RUN[:json] x.report("json_coder") { coder.load(json_output) } if RUN[:json_coder] - x.report("oj") { Oj.load(json_output) } if RUN[:oj] - x.report("Oj::Parser") { Oj::Parser.new(:usual).parse(json_output) } if RUN[:oj] - x.report("rapidjson") { RapidJSON.parse(json_output) } if RUN[:rapidjson] + + if defined?(Oj) + x.report("oj") { Oj.load(json_output) } if RUN[:oj] + x.report("Oj::Parser") { Oj::Parser.new(:usual).parse(json_output) } if RUN[:oj] + end + + if defined?(RapidJSON) + x.report("rapidjson") { RapidJSON.parse(json_output) } if RUN[:rapidjson] + end + x.compare!(order: :baseline) end puts