Skip to content

Instantly share code, notes, and snippets.

@lucianghinda
Created September 7, 2022 06:51
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 lucianghinda/f1b99b4b0a0a6a8849a2a5feb99bdc8f to your computer and use it in GitHub Desktop.
Save lucianghinda/f1b99b4b0a0a6a8849a2a5feb99bdc8f to your computer and use it in GitHub Desktop.
Benchmark Ruby Array#bsearch
# frozen_string_literal: true
require "benchmark"
require "benchmark/ips"
array = Array.new(1000) { Random.rand(100) }.sort
n = 50_000
Benchmark.bmbm do |benchmark|
benchmark.report("bsearch") do
n.times do
array.bsearch { _1 >= 6 }
end
end
benchmark.report("find") do
n.times do
array.find { _1 >= 6 }
end
end
benchmark.report("select.first") do
n.times do
array.select { _1 >= 6 }.first
end
end
benchmark.report("find_index") do
n.times do
array.find_index { _1 >= 6 }
end
end
end
puts ""
Benchmark.ips do |benchmark|
benchmark.report("bsearch") do
n.times do
array.bsearch { _1 >= 6 }
end
end
benchmark.report("find") do
n.times do
array.find { _1 >= 6 }
end
end
benchmark.report("select.first") do
n.times do
array.select { _1 >= 6 }.first
end
end
benchmark.report("find_index") do
n.times do
array.find_index { _1 >= 6 }
end
end
benchmark.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment