Last active
September 13, 2019 02:39
-
-
Save montanalow/e4e19fbef3ef9bdd9ca8dc1113525b2f to your computer and use it in GitHub Desktop.
Ruby hash vs instance variable benchmark
This file contains hidden or 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' | |
| $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 | |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
results: