文字和构造函数之间的区别?([] 与 Array.new 和 {} 与 Hash.new) [英] Differences between literals and constructors? ([] vs Array.new and {} vs Hash.new)

查看:31
本文介绍了文字和构造函数之间的区别?([] 与 Array.new 和 {} 与 Hash.new)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很想知道 [] 和 Array.new 以及 {} 和 Hash.new 之间的更多区别

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.

干杯.

推荐答案

使用 Hash.new 您可以为未设置的键设置散列的默认值.如果您正在做统计,这非常有用,因为 Hash.new(0) 将让您增加键而不显式初始化它们.

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.

这篇关于文字和构造函数之间的区别?([] 与 Array.new 和 {} 与 Hash.new)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆