Skip to content

Instantly share code, notes, and snippets.

@andriusch
Forked from miharekar/benchmark.rb
Last active August 27, 2015 09:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriusch/d5324a154662aa59a7e8 to your computer and use it in GitHub Desktop.
Save andriusch/d5324a154662aa59a7e8 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
1000.times { test }
end
end
class Bar
def initialize(test)
@test = test
end
def read
1000.times { @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
@andriusch
Copy link
Author

Calculating -------------------------------------
                attr     2.224k i/100ms
            instance     2.680k i/100ms
-------------------------------------------------
                attr     23.315k (± 0.4%) i/s -    233.520k
            instance     27.291k (± 0.5%) i/s -    273.360k

Comparison:
            instance:    27291.5 i/s
                attr:    23314.7 i/s - 1.17x slower

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