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.
The curly brackets { } are used to initialize hashes. The documentation for initializer case of { } is in ri Hash::[] The square brackets are also commonly used as a method in many core ruby classes, like Array, Hash, String, and others.
In short, Hash. new(some_value) sets a default value of some_value for every key that does not exist in the hash, Hash. new {|hash, key| block } creates a new default object for every key that does not exist in the hash, and Hash. new() or {} sets nil for every key.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With