Skip to content

Instantly share code, notes, and snippets.

@miharekar
Created August 27, 2015 09:01
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 miharekar/9b618e709855f8b25771 to your computer and use it in GitHub Desktop.
Save miharekar/9b618e709855f8b25771 to your computer and use it in GitHub Desktop.
attr_reader vs instance var
require 'benchmark/ips'
class Foo
attr_reader :test
def initialize(test)
@test = test
end
def read
test
end
end
class Bar
def initialize(test)
@test = test
end
def read
@test
end
end
Benchmark.ips do |x|
x.config(time: 10)
foo = Foo.new('lalala')
bar = Bar.new('lalala')
x.report('attr') { foo.read }
x.report('instance') { bar.read }
x.compare!
end
@miharekar
Copy link
Author

Calculating -------------------------------------
                attr   140.015k i/100ms
            instance   140.783k i/100ms
-------------------------------------------------
                attr      7.790M (± 8.0%) i/s -     77.428M
            instance      7.864M (±11.8%) i/s -     77.290M

Comparison:
            instance:  7864065.9 i/s
                attr:  7789875.8 i/s - 1.01x slower

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