मैं सिर्फ बराबर गेटर/सेटर-तरीकों के खिलाफ attr_accessor परीक्षण किया:रूबी attr_accessor बनाम गेटर/सेटर बेंचमार्क: एक्सेसर तेजी से क्यों है?
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
काफी तेजी है। क्या कोई कृपया कुछ ज्ञान साझा कर सकता है, ऐसा क्यों है?
बेंचमार्किंग कोड के लिए, आप केवल stdlib मॉड्यूल बेंचमार्क का उपयोग कर सकते हैं: http://www.ruby-doc.org/stdlib-1.9.3/libdoc/benchmark/rdoc/Benchmark.html#method-c-bm। नोट के लिए –
Thx। मॉड्यूल की तरह लगता है मुझे अगली बार कोशिश करनी चाहिए:] – rhavin