Created
February 11, 2020 21:22
-
-
Save drewtempelmeyer/620c168e9c1d1370a3c93e8d35a84b36 to your computer and use it in GitHub Desktop.
Array#detect vs Hash#[]
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
# This benchmark assumes we're consistently looking for the last | |
# item in the array. | |
# | |
# If you want to use a random number, use i = rand(1..20) in both | |
# reports. | |
require "benchmark" | |
n = 500_000 | |
arr = (1..20).map { |i| { id: i } } | |
hsh = Hash[arr.map { |i| [i[:id], i] }] | |
Benchmark.bmbm do |x| | |
x.report("Array#detect") do | |
n.times do | |
i = 20 | |
arr.detect { |item| item[:id] == i } | |
end | |
end | |
x.report("Hash#[]") do | |
n.times do | |
i = 20 | |
hsh[i] | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Results