Skip to content

Instantly share code, notes, and snippets.

@schneems
Last active November 3, 2018 13:51
Show Gist options
  • Save schneems/5d5df30d1f7e13529712 to your computer and use it in GitHub Desktop.
Save schneems/5d5df30d1f7e13529712 to your computer and use it in GitHub Desktop.

TIL attr_* methods are optomized.

class Whatever
  def foo
    @foo
  end

  attr_reader :bar
end

require "benchmark/ips"

OBJ = Whatever.new
Benchmark.ips do |x|
  x.report("method") { OBJ.foo }
  x.report("attr_reader") { OBJ.bar }
end

Result

Calculating -------------------------------------
              method   116.923k i/100ms
         attr_reader   112.147k i/100ms
-------------------------------------------------
              method      5.848M (±16.1%) i/s -     28.412M
         attr_reader      7.762M (±16.4%) i/s -     37.569M

The attr_reader method is much faster

Thanks @pat_shaughnessy in Ruby Under a Microscope

@benoittgt
Copy link

On Ruby 2.5.3

Warming up --------------------------------------
              method   297.389k i/100ms
         attr_reader   312.447k i/100ms
Calculating -------------------------------------
              method     10.093M (± 4.9%) i/s -     50.556M in   5.021785s
         attr_reader     10.863M (± 6.6%) i/s -     54.053M in   5.000887s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment