Skip to content

Instantly share code, notes, and snippets.

@frsyuki
Last active August 29, 2015 14:04
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 frsyuki/3aa24a96912bc20a54ac to your computer and use it in GitHub Desktop.
Save frsyuki/3aa24a96912bc20a54ac to your computer and use it in GitHub Desktop.
require 'benchmark'
LOOP = 500000
NKEYS = 20
vals = (0..NKEYS).map {|i| "val#{i}" }
keys = (0..NKEYS).map {|i| "col#{i}" }
S = Struct.new(*keys.map {|k| k.to_sym })
Benchmark.bmbm do |x|
x.report("Struct#[]=") {
LOOP.times do
obj = S.new
(0..NKEYS).each {|i| obj[keys[i]] = vals[i] }
end
}
x.report("Struct.new") {
LOOP.times do
S.new *(0..NKEYS).map {|i| vals[i] }
end
}
x.report("Struct.new + codegen") {
code = eval("proc {|vals| S.new(#{(0..NKEYS).map {|i| "vals[#{i}]" }.join(',')}) }")
LOOP.times do
code.call(vals)
end
}
x.report("Hash#[]=") {
LOOP.times do
obj = {}
(0..NKEYS).each {|i| obj[keys[i]] = vals[i] }
end
}
x.report("Hash.new(zip)") {
LOOP.times do
vals_array = (0..NKEYS).map {|i| vals[i] }
Hash[keys.zip(vals_array)]
end
}
x.report("Hash.new + codegen") {
kv_code = (0..NKEYS).map {|i| "#{keys[i].dump},vals[#{i}]" }
code = eval("proc {|vals| Hash[#{kv_code.join(',')}] }")
LOOP.times do
code.call(vals)
end
}
end
__END__
Rehearsal --------------------------------------------------------
Struct#[]= 2.740000 0.000000 2.740000 ( 2.748829)
Struct.new 1.540000 0.000000 1.540000 ( 1.549932)
Struct.new + codegen 0.390000 0.010000 0.400000 ( 0.387977)
Hash#[]= 4.350000 0.000000 4.350000 ( 4.360114)
Hash.new(zip) 5.820000 0.010000 5.830000 ( 5.829954)
Hash.new + codegen 4.100000 0.000000 4.100000 ( 4.118849)
---------------------------------------------- total: 18.960000sec
user system total real
Struct#[]= 2.760000 0.010000 2.770000 ( 2.766344)
Struct.new 1.590000 0.000000 1.590000 ( 1.612082)
Struct.new + codegen 0.370000 0.000000 0.370000 ( 0.374896)
Hash#[]= 4.400000 0.010000 4.410000 ( 4.415043)
Hash.new(zip) 5.890000 0.010000 5.900000 ( 5.904067)
Hash.new + codegen 4.110000 0.000000 4.110000 ( 4.138564)
ruby 2.1.2p95 (2014-05-08 revision 45877) [x86_64-darwin13.0]
Darwin xcore 13.2.0 Darwin Kernel Version 13.2.0: Thu Apr 17 23:03:13 PDT 2014; root:xnu-2422.100.13~1/RELEASE_X86_64 x86_64 i386 MacBookPro10,1 Darwin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment