加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby attr_accessor与getter / setter基准:为什么访问器更快?

发布时间:2020-12-16 21:38:23 所属栏目:百科 来源:网络整理
导读:我刚刚测试了attr_accessor对等同的getter / setter方法: class A # we define two R/W attributes with accessors attr_accessor :acc,:bcc # we define two attributes with getter/setter-functions def dirA=(d); @dirA=d; end def dirA; @dirA; end de
我刚刚测试了attr_accessor对等同的getter / setter方法:
class A
  # we define two R/W attributes with accessors
  attr_accessor :acc,:bcc

  # we define two attributes with getter/setter-functions
  def dirA=(d); @dirA=d; end
  def dirA; @dirA; end
  def dirB=(d); @dirB=d; end
  def dirB; @dirB; end
end

varA   = A.new
startT = 0
dirT   = 0
accT   = 0

# now we do 100 times the same benchmarking
# where we do the same assignment operation
# 50000 times
100.times do
  startT = Time.now.to_f
  50000.times do |i|
    varA.dirA = i
    varA.dirB = varA.dirA
  end
  dirT += (Time.now.to_f - startT)

  startT = Time.now.to_f
  50000.times do |i|
    varA.acc = i
    varA.bcc = varA.acc
  end
  accT += (Time.now.to_f - startT)
end

puts "direct:   %10.4fs" % (dirT/100)
puts "accessor: %10.4fs" % (accT/100)

程序输出是:

direct:       0.2640s
accessor:     0.1927s

所以attr_accessor明显更快.有人可以分享一些智慧,为什么这样呢?

解决方法

没有深入了解差异,至少可以说 attr_accessor(和attr_reader和attr_writer)在C中实现,您可以通过切换该页面上的源来看到.您的方法将在Ruby中实现,并且Ruby方法具有比本机C函数更多的调用开销.

这是一篇解释why Ruby method dispatch tends to be slow的文章.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读