Created
August 7, 2018 02:22
-
-
Save mchung/6b454874f9d3ecb8e09d53c721f7d90f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'benchmark/ips' | |
class SelfRuby | |
attr_accessor :foo | |
def initialize | |
self.foo = 1 | |
end | |
end | |
# SLOWEST! | |
class InstRuby | |
def initialize | |
@foo = 1 | |
end | |
def foo | |
@foo | |
end | |
end | |
class CombRuby | |
attr_accessor :foo | |
def initialize | |
@foo = 1 | |
end | |
end | |
a = SelfRuby.new | |
b = InstRuby.new | |
c = CombRuby.new | |
Benchmark.ips do |x| | |
x.report 'self.foo attr access' do | |
a.foo | |
end | |
x.report '@foo no attr' do | |
b.foo | |
end | |
x.report '@foo w/ attr' do | |
c.foo | |
end | |
x.compare! | |
end | |
# › ruby bm.rb | |
# Warming up -------------------------------------- | |
# self.foo attr access 323.704k i/100ms | |
# @foo no attr 313.221k i/100ms | |
# @foo w/ attr 324.119k i/100ms | |
# Calculating ------------------------------------- | |
# self.foo attr access 11.303M (± 2.6%) i/s - 56.648M in 5.015020s | |
# @foo no attr 10.319M (± 2.4%) i/s - 51.681M in 5.011602s | |
# @foo w/ attr 11.484M (± 2.1%) i/s - 57.693M in 5.026025s | |
# | |
# Comparison: | |
# @foo w/ attr: 11483943.6 i/s | |
# self.foo attr access: 11303406.2 i/s - same-ish: difference falls within error | |
# @foo no attr: 10318936.3 i/s - 1.11x slower | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment