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
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.
Robert already mentioned the default value of the Hash.new
You may also use compley 'default'-values with the block variant of Hash.new
:
x = Hash.new { |hash, key|
hash[key] = key * 2
}
p x #-> {}
p x[1] #-> 2
p x #-> {1=>2}
Array.new
can also be used to get default values:
p Array.new(5, :a) #-> [:a, :a, :a, :a, :a]
So for half a million times they all ran "very quickly". I prefer literals in any language ([], {}, 0, "", etc.) but the literals can't do everything (see the documentation for the other constructor forms). Write clean code, and be consistent: there is no issue here :)
However, I suspect the literals avoid a constant lookup and a method call which results in them being faster, at least in that particular implementation .. (someone with more smarts than me could look at the intermediate AST generated to prove/disprove this.)
That is, what if Hash
resolved to a custom class or Hash.new
was replaced with a custom method? Can't do that with {}
. In addition, the methods have to deal with additional arguments (or blocks) while the literals do not.