Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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