Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mathieujobin/6cafc62c5d6ee39aadfff74c5090989a to your computer and use it in GitHub Desktop.
Save mathieujobin/6cafc62c5d6ee39aadfff74c5090989a to your computer and use it in GitHub Desktop.
Simple benchmark comparing Oj and JSON::Ext (core ruby)
#! /usr/env ruby
require "benchmark"
require "oj"
require "json"
require "rbconfig"
puts "Host OS: #{RbConfig::CONFIG['host_os']}"
puts "Ruby Version #{RUBY_VERSION}"
puts "OJ version #{Oj::VERSION}"
puts "JSON version #{JSON::VERSION}\n"
json_string = <<~JSON
{"a":"Alpha","b":true,"c":12345,"d":[true,[false,[-123456789,null],3.9676,["Something else.",false],null]],"e":{"zero":null,"one":1,"two":2,"three":[3],"four":[0,1,2,3,4]},"f":null,"h":{"a":{"b":{"c":{"d":{"e":{"f":{"g":null}}}}}}},"i":[[[[[[[null]]]]]]]}
JSON
# use JSON to craft the object (just for a baseline in compatibility)
ruby_obj = JSON.load(json_string)
puts "⚠️ - JSON.load and Oj.load do not produce equivalent JSON" unless ruby_obj == Oj.load(json_string)
n = 100_000
oj_report = nil
json_report = nil
puts "Number of iterations: #{n}"
Benchmark.bm(14, "OJ-per-parse", "JSON-per-parse") do |test|
oj_report = test.report("Oj.load") { n.times { Oj.load(json_string) } }
json_report = test.report("JSON.load") { n.times { JSON.load(json_string) } }
[oj_report/n, json_report/n]
end
puts "Oj parses/sec #{n/oj_report.total}"
puts "JSON parses/sec #{n/json_report.total}"
Benchmark.bm(14, "OJ-per-gen", "JSON-per-gen") do |test|
oj_report = test.report("Oj.dump") { n.times { Oj.dump(ruby_obj) } }
json_report = test.report("JSON.dump") { n.times { JSON.dump(ruby_obj) } }
[oj_report/n, json_report/n]
end
puts "Oj gens/sec #{n/oj_report.total}"
puts "JSON gens/sec #{n/json_report.total}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment