Skip to content

Instantly share code, notes, and snippets.

@drewtempelmeyer
Created February 11, 2020 21:22
Show Gist options
  • Save drewtempelmeyer/620c168e9c1d1370a3c93e8d35a84b36 to your computer and use it in GitHub Desktop.
Save drewtempelmeyer/620c168e9c1d1370a3c93e8d35a84b36 to your computer and use it in GitHub Desktop.
Array#detect vs Hash#[]
# 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
@drewtempelmeyer
Copy link
Author

Results

                   user     system      total        real
Array#detect   0.683306   0.000014   0.683320 (  0.683338)
Hash#[]        0.023468   0.000000   0.023468 (  0.023469)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment