Differences between literals and constructors? ([] vs Array.new and {} vs Hash.new)

前端 未结 3 1083
遥遥无期
遥遥无期 2021-02-05 05:39

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



        
3条回答
  •  孤独总比滥情好
    2021-02-05 06:34

    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.

提交回复
热议问题