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
On Ruby 2.5.3