Created
April 12, 2022 21:19
-
-
Save wspurgin/21a651906155254d11de6326288fd119 to your computer and use it in GitHub Desktop.
Simple benchmark comparing Oj and JSON::Ext (core ruby)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#! /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}" |
mathieujobin
commented
Mar 23, 2023
❯ ruby json_benchmark.rb
Host OS: darwin24
Ruby Version 3.3.6
OJ version 3.16.7
JSON version 2.9.0
Number of iterations: 100000
user system total real
Oj.load 0.252782 0.009167 0.261949 ( 0.261958)
JSON.load 0.218810 0.005573 0.224383 ( 0.224385)
OJ-per-parse 0.000003 0.000000 0.000003 ( 0.000003)
JSON-per-parse 0.000002 0.000000 0.000002 ( 0.000002)
Oj parses/sec 381753.7001477387
JSON parses/sec 445666.5611922472
user system total real
Oj.dump 0.117130 0.004890 0.122020 ( 0.123199)
JSON.dump 0.133768 0.005153 0.138921 ( 0.138924)
OJ-per-gen 0.000001 0.000000 0.000001 ( 0.000001)
JSON-per-gen 0.000001 0.000000 0.000001 ( 0.000001)
Oj gens/sec 819537.7806916893
JSON gens/sec 719833.5744775808
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment