Skip to content

Instantly share code, notes, and snippets.

@montanalow
Last active September 13, 2019 02:39
Show Gist options
  • Select an option

  • Save montanalow/e4e19fbef3ef9bdd9ca8dc1113525b2f to your computer and use it in GitHub Desktop.

Select an option

Save montanalow/e4e19fbef3ef9bdd9ca8dc1113525b2f to your computer and use it in GitHub Desktop.
Ruby hash vs instance variable benchmark
require 'benchmark'
$CYCLE = 10_000_000
class HashString
def initialize
@attrs = {}
end
def attr=(value)
@attrs["attr"] = value
end
def attr
@attrs["attr"]
end
end
class HashSymbol
def initialize
@attrs = {}
end
def attr=(value)
@attrs[:attr] = value
end
def attr
@attrs[:attr]
end
end
class Dynamic
def attr=(value)
instance_variable_set(:@attr, value)
end
def attr
instance_variable_get(:@attr)
end
end
class Attr
def attr=(value)
@attr = value
end
def attr
@attr
end
end
class AttrAccessor
attr_accessor :attr
end
hash_string = HashString.new
hash_symbol = HashSymbol.new
dynamic = Dynamic.new
attr = Attr.new
attr_accessor = AttrAccessor.new
Benchmark.bmbm do |x|
x.report "hash_string" do
$CYCLE.times {|x| hash_string.attr= 'foo'; hash_string.attr }
end
x.report "hash_symbol" do
$CYCLE.times {|x| hash_symbol.attr= 'foo'; hash_string.attr }
end
x.report "hash_var" do
$CYCLE.times {|x| dynamic.attr= 'foo'; dynamic.attr }
end
x.report "hash_attr" do
$CYCLE.times {|x| attr.attr= 'foo'; attr.attr }
end
x.report "attr_accessor" do
$CYCLE.times {|x| attr_accessor.attr= 'foo'; attr_accessor.attr }
end
end
@montanalow

montanalow commented Sep 13, 2019

Copy link
Copy Markdown
Author

results:

Rehearsal -------------------------------------------------
hash_string     1.916145   0.013042   1.929187 (  1.931123)
hash_symbol     1.691964   0.001916   1.693880 (  1.695300)
hash_var        1.651257   0.001707   1.652964 (  1.654485)
hash_attr       1.126608   0.000957   1.127565 (  1.128265)
attr_accessor   1.018322   0.000909   1.019231 (  1.020059)
---------------------------------------- total: 7.422827sec

                    user     system      total        real
hash_string     1.981905   0.002997   1.984902 (  1.986935)
hash_symbol     1.733741   0.001629   1.735370 (  1.736725)
hash_var        1.651719   0.001761   1.653480 (  1.654465)
hash_attr       1.127937   0.001541   1.129478 (  1.130193)
attr_accessor   1.039764   0.001949   1.041713 (  1.043536)

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