Skip to content

Instantly share code, notes, and snippets.

@okabe-yuya
Created May 16, 2023 11:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okabe-yuya/63a55c9480f80e1b434b7a63029715c8 to your computer and use it in GitHub Desktop.
Save okabe-yuya/63a55c9480f80e1b434b7a63029715c8 to your computer and use it in GitHub Desktop.
配列からハッシュを作る際のパフィーマンスを測定するコードです
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