Skip to content

Instantly share code, notes, and snippets.

@nicoolas25
Last active December 21, 2015 07:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nicoolas25/6271100 to your computer and use it in GitHub Desktop.
Save nicoolas25/6271100 to your computer and use it in GitHub Desktop.
Compare an access speed between an instance variable and an accessor.
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