nicoolas25
8/19/2013 - 4:33 PM

Compare an access speed between an instance variable and an accessor.

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