Created
September 7, 2022 06:51
-
-
Save lucianghinda/f1b99b4b0a0a6a8849a2a5feb99bdc8f to your computer and use it in GitHub Desktop.
Benchmark Ruby Array#bsearch
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
# 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