Skip to content

Instantly share code, notes, and snippets.

@godfat
Created July 5, 2011 17:17
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save godfat/1065318 to your computer and use it in GitHub Desktop.
Save godfat/1065318 to your computer and use it in GitHub Desktop.
require 'benchmark'
FooBar = Struct.new(:foo, :bar)
data = (0..9999).map{ |i| FooBar.new(i, i+1) }
Benchmark.bmbm do |b|
b.report('inject(fold)'){
1000.times{ data.inject({}){|h, d| h[d.foo] = d.bar; h }}}
b.report('Hash+map'){
1000.times{ Hash[data.map {|d| [d.foo, d.bar]} ]}}
end
00:58 /p/tmp> jruby bm.rb
Rehearsal ------------------------------------------------
inject(fold) 2.898000 0.000000 2.898000 ( 2.821000)
Hash+map 2.412000 0.000000 2.412000 ( 2.412000)
--------------------------------------- total: 5.310000sec
user system total real
inject(fold) 2.477000 0.000000 2.477000 ( 2.477000)
Hash+map 2.292000 0.000000 2.292000 ( 2.292000)
01:16 /p/tmp> jruby bm.rb
Rehearsal ------------------------------------------------
inject(fold) 16.940000 0.000000 16.940000 ( 16.864000)
Hash+map 16.694000 0.000000 16.694000 ( 16.694000)
-------------------------------------- total: 33.634000sec
user system total real
inject(fold) 16.385000 0.000000 16.385000 ( 16.385000)
Hash+map 16.606000 0.000000 16.606000 ( 16.606000)
01:19 /p/tmp> jruby --server bm.rb
Rehearsal ------------------------------------------------
inject(fold) 15.480000 0.000000 15.480000 ( 15.405000)
Hash+map 13.348000 0.000000 13.348000 ( 13.348000)
-------------------------------------- total: 28.828000sec
user system total real
inject(fold) 15.089000 0.000000 15.089000 ( 15.089000)
Hash+map 12.999000 0.000000 12.999000 ( 12.999000)
01:07 /p/tmp> ruby bm.rb
Rehearsal ------------------------------------------------
inject(fold) 6.120000 0.150000 6.270000 ( 6.256518)
Hash+map 6.650000 0.020000 6.670000 ( 6.672158)
-------------------------------------- total: 12.940000sec
user system total real
inject(fold) 6.100000 0.140000 6.240000 ( 6.231792)
Hash+map 6.500000 0.020000 6.520000 ( 6.499045)
01:08 /p/tmp> rbx bm.rb
Rehearsal ------------------------------------------------
inject(fold) 14.370269 0.136047 14.506316 ( 14.640777)
Hash+map 26.914388 0.131548 27.045936 ( 27.099733)
-------------------------------------- total: 41.552252sec
user system total real
inject(fold) 14.399943 0.115520 14.515463 ( 14.516802)
Hash+map 27.300467 0.124162 27.424629 ( 27.511583)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment