Skip to content

Instantly share code, notes, and snippets.

@byroot
Created October 28, 2024 18:50
Show Gist options
  • Select an option

  • Save byroot/a79fc8008c5c866d90defe4c9644d4e1 to your computer and use it in GitHub Desktop.

Select an option

Save byroot/a79fc8008c5c866d90defe4c9644d4e1 to your computer and use it in GitHub Desktop.

Revisions

  1. byroot created this gist Oct 28, 2024.
    31 changes: 31 additions & 0 deletions json_small_bench.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,31 @@
    require 'benchmark/ips'
    require 'oj'
    require 'json'

    puts "Ruby version: #{RUBY_VERSION}"
    puts "Oj version: #{Oj::VERSION}"
    puts "JSON version: #{JSON::VERSION}"

    json_encoder = JSON::State.new(JSON.dump_default_options)
    # Sample data to hash - using varied data types
    test_data = [1, "string", { a: 1, b: 2 }, [3, 4, 5]]

    Oj.default_options = Oj.default_options.merge(mode: :compat)

    Benchmark.ips do |x|
    x.config(time: 5, warmup: 2)

    x.report("Oj") do
    Oj.dump(test_data)
    end

    x.report("JSON reuse") do
    json_encoder.generate(test_data)
    end

    x.report("JSON") do
    JSON.dump(test_data)
    end

    x.compare!(order: :baseline)
    end
    18 changes: 18 additions & 0 deletions results.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    $ ruby --yjit /tmp/foo.rb
    Ruby version: 3.3.4
    Oj version: 3.16.6
    JSON version: 2.7.3
    ruby 3.3.4 (2024-07-09 revision be1089c8ec) +YJIT [arm64-darwin23]
    Warming up --------------------------------------
    Oj 535.182k i/100ms
    JSON reuse 447.109k i/100ms
    JSON 249.109k i/100ms
    Calculating -------------------------------------
    Oj 5.792M (± 0.5%) i/s (172.64 ns/i) - 29.435M in 5.081754s
    JSON reuse 4.793M (± 1.3%) i/s (208.65 ns/i) - 24.144M in 5.038591s
    JSON 2.676M (± 1.0%) i/s (373.74 ns/i) - 13.452M in 5.027962s

    Comparison:
    Oj: 5792440.1 i/s
    JSON reuse: 4792621.8 i/s - 1.21x slower
    JSON: 2675676.3 i/s - 2.16x slower