Skip to content

Instantly share code, notes, and snippets.

@sorentwo
Created April 10, 2015 21:12
Show Gist options
  • Save sorentwo/5075533aa1dd3810b1db to your computer and use it in GitHub Desktop.
Save sorentwo/5075533aa1dd3810b1db to your computer and use it in GitHub Desktop.
Compare performance of ||= vs Hash.new for default arrays
require 'benchmark'
N = 10_000
C = %w[a b c] * 100
Benchmark.bmbm do |x|
x.report "||=" do
N.times do
C.each_with_object({}) do |val, memo|
memo[val] ||= []
memo[val] << val
end
end
end
x.report "Hash.new" do
N.times do
hash = Hash.new { |h, k| h[k] = [] }
C.each_with_object(hash) do |val, memo|
memo[val] << val
end
end
end
end
Rehearsal --------------------------------------------
||= 0.860000 0.010000 0.870000 ( 0.867042)
Hash.new 0.620000 0.000000 0.620000 ( 0.623793)
----------------------------------- total: 1.490000sec
user system total real
||= 0.850000 0.010000 0.860000 ( 0.856867)
Hash.new 0.600000 0.000000 0.600000 ( 0.603829)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment