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
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.