Ruby attr_accessor与getter/setter基准测试:为什么accessor更快? [英] Ruby attr_accessor vs. getter/setter benchmark: why is accessor faster?
本文介绍了Ruby attr_accessor与getter/setter基准测试:为什么accessor更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚针对等效的getter/setter方法测试了attr_accessor:
I just tested attr_accessor against equivalent getter/setter-methods:
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
明显更快.有人可以分享一些智慧吗,为什么会这样呢?
So the attr_accessor
is significantly faster. could someone please share some wisdom, why this is so?
推荐答案
Without deeply understanding the differences, I can at least say that attr_accessor
(and attr_reader
and attr_writer
) are implemented in C, as you can see by toggling the source on that page. Your methods will be implemented in Ruby, and Ruby methods have more call overhead than native C functions.
这是一篇文章,解释为什么Ruby方法的分发速度会很慢.
这篇关于Ruby attr_accessor与getter/setter基准测试:为什么accessor更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文