Skip to content

Instantly share code, notes, and snippets.

@SamSaffron
Created May 4, 2021 23:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamSaffron/e38a3438aa4a27a3f95c5c7386e2cd40 to your computer and use it in GitHub Desktop.
Save SamSaffron/e38a3438aa4a27a3f95c5c7386e2cd40 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
require 'json'
require 'oj'
numbers_as_string_json = ("," + (1..10000).to_a.join(",") + ",").to_json
numbers_json = (1..10000).to_a.to_json
Benchmark.ips do |x|
x.report("Numbers binary search") do |i|
while i > 0
numbers = JSON.parse(numbers_json)
numbers.bsearch { |x| x == 77 }
i -= 1
end
end
x.report("Numbers include") do |i|
while i > 0
numbers = JSON.parse(numbers_json)
numbers.include?(5000)
i -= 1
end
end
x.report("Numbers binary search Oj") do |i|
while i > 0
numbers = Oj.load(numbers_json)
numbers.bsearch { |x| x == 77 }
i -= 1
end
end
x.report("Numbers include Oj") do |i|
while i > 0
numbers = Oj.load(numbers_json)
numbers.include?(5000)
i -= 1
end
end
x.report("String hack") do |i|
while i > 0
string = JSON.parse(numbers_as_string_json)
string.include?(",5000,")
i -= 1
end
end
x.report("String hack Oj") do |i|
while i > 0
string = Oj.load(numbers_as_string_json)
string.include?(",5000,")
i -= 1
end
end
x.compare!
end
# Comparison:
# String hack Oj: 28291.9 i/s
# String hack: 20373.9 i/s - 1.39x (± 0.00) slower
# Numbers binary search Oj: 3736.4 i/s - 7.57x (± 0.00) slower
# Numbers include Oj: 3492.2 i/s - 8.10x (± 0.00) slower
# Numbers binary search: 2264.1 i/s - 12.50x (± 0.00) slower
# Numbers include: 2164.2 i/s - 13.07x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment