Last active
December 21, 2015 07:28
-
-
Save nicoolas25/6271100 to your computer and use it in GitHub Desktop.
Compare an access speed between an instance variable and an accessor.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark' | |
n = 5000000 | |
class A | |
def initialize(attribute) | |
@attribute = attribute | |
end | |
def none | |
end | |
def method | |
attribute + attribute | |
end | |
def direct | |
@attribute + @attribute | |
end | |
private | |
attr_reader :attribute | |
end | |
a = A.new(10) | |
n = 5000000 | |
Benchmark.bm(10) do |x| | |
x.report('none:') { n.times do a.none end } | |
x.report('method:') { n.times do a.method end } | |
x.report('direct:') { n.times do a.direct end } | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment