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

前端 未结 3 1082
遥遥无期
遥遥无期 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:15

    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.

    0 讨论(0)
  • 2021-02-05 06:15

    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]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题