From: Robert Klemme Date: 2011-01-13T21:15:24+09:00 Subject: Re: Why {} is much faster than Hash.new ? On Thu, Jan 13, 2011 at 12:05 PM, Iņaki Baz Castillo wrote: > Hi, a simple benchmark: > > Benchmark.realtime { 1000000.times { @m = Hash.new } } > => 0.6552023887634277 > > Benchmark.realtime { 1000000.times { @m = {} } } > => 0.17668819427490234 > > I would like to know why {} is so much faster. I can understand that > Hash.initialize method must inspect is an argument is given and so, is > just due to it? I can imagine that's about right. Another benchmark: 13:10:40 Temp$ ruby19 bm.rb Rehearsal -------------------------------------------------- Hash.new 1.297000 0.000000 1.297000 ( 1.293000) Hash 0.125000 0.000000 0.125000 ( 0.127000) Hash.nil? 0.187000 0.000000 0.187000 ( 0.186000) {} 0.188000 0.000000 0.188000 ( 0.191000) ----------------------------------------- total: 1.797000sec user system total real Hash.new 1.296000 0.000000 1.296000 ( 1.292000) Hash 0.125000 0.000000 0.125000 ( 0.127000) Hash.nil? 0.188000 0.000000 0.188000 ( 0.185000) {} 0.187000 0.000000 0.187000 ( 0.191000) 13:10:50 Temp$ cat bm.rb require 'benchmark' R = 1_000_000 Benchmark.bmbm 15 do |b| b.report "Hash.new" do R.times { Hash.new } end b.report "Hash" do R.times { Hash } end b.report "Hash.nil?" do R.times { Hash.nil? } end b.report "{}" do R.times { {} } end end 13:10:52 Temp$ Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/