Ruby的attr_accessor对比的getter / setter基准:为什么访问速度更快?(

2019-07-04 00:52发布

我只是测试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显著快。 可能有人请分享一些智慧,为什么会这样?

Answer 1:

如果没有深入了解的差异,我至少可以说, attr_accessor (和attr_readerattr_writer )是用C语言实现,你可以通过切换该网页上的源代码看到。 你的方法将在Ruby的实现,Ruby方法有更多的调用开销比原生的C函数。

下面是一篇文章,解释为什么Ruby的方法调度趋于缓慢 。



文章来源: Ruby attr_accessor vs. getter/setter benchmark: why is accessor faster?