Created
May 16, 2023 11:42
-
-
Save okabe-yuya/63a55c9480f80e1b434b7a63029715c8 to your computer and use it in GitHub Desktop.
配列からハッシュを作る際のパフィーマンスを測定するコードです
This file contains 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
require 'benchmark' | |
list = (1..10000).to_a | |
Benchmark.bm(20) do |x| | |
x.report('for:') do | |
hash = {} | |
for n in list do | |
hash[n.to_s] = n * 2 | |
end | |
end | |
x.report('each:') do | |
hash = {} | |
list.each do |n| | |
hash[n.to_s] = n * 2 | |
end | |
end | |
x.report('each_with_object:') do | |
list.each_with_object({}) do |n, hash| | |
hash[n.to_s] = n * 2 | |
end | |
end | |
x.report('reduce:') do | |
list.reduce({}) do |hash, n| | |
hash[n.to_s] = n * 2 | |
hash | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment