I was curious to know more differences between [] and Array.new and {} and Hash.new
I ran same benchmarks on it and seems like the shorthands are winners
require 'benchmark'
many = 500000
Benchmark.bm do |b|
b.report("[] \t") {many.times { [].object_id }}
b.report("Array.new \t") { many.times { Array.new.object_id }}
b.report("{} \t") {many.times { {}.object_id }}
b.report("Hash.new\t") { many.times { Hash.new.object_id }}
end
user system total real
[] 0.080000 0.000000 0.080000 ( 0.079287)
Array.new 0.180000 0.000000 0.180000 ( 0.177105)
{} 0.080000 0.000000 0.080000 ( 0.079467)
Hash.new 0.260000 0.000000 0.260000 ( 0.264796)
I personally like to use the shorthand one’s [] and {} , the code looks so cool and readable.
Any other pointer what is the difference between them? what happens behind scene that make it so better, and suggestions if any when to use which?
I found this link but was looking to get more info.
cheers.
With Hash.new you can set the default value of the hash for unset keys. This is quite useful if you’re doing statistics, because
Hash.new(0)will let you increment keys without explicitly initializing them.