Last active
September 2, 2024 15:36
-
-
Save tiagoamaro/c82a27aceedfc901b081 to your computer and use it in GitHub Desktop.
ActiveSupport's HashWithIndifferentAccess access benchmark vs common Ruby Hash
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 'active_support/all' | |
| require 'benchmark/ips' | |
| Benchmark.ips do |x| | |
| x.config(time: 5, warmup: 2) | |
| @hash_with_indifferent_access = ActiveSupport::HashWithIndifferentAccess.new(a: 1) | |
| @hash = Hash[a: 2] | |
| x.report("Common Hash access") do | |
| @hash.fetch :a | |
| end | |
| x.report("HashWithIndifferentAccess#fetch Symbol") do | |
| @hash_with_indifferent_access.fetch :a | |
| end | |
| x.report("HashWithIndifferentAccess#fetch String") do | |
| @hash_with_indifferent_access.fetch 'a' | |
| end | |
| x.report("HashWithIndifferentAccess #[] Symbol") do | |
| @hash_with_indifferent_access[:a] | |
| end | |
| x.report("HashWithIndifferentAccess #[] String") do | |
| @hash_with_indifferent_access['a'] | |
| end | |
| # Compare the iterations per second of the various reports! | |
| x.compare! | |
| end | |
| # Results | |
| # ▶ ruby hash_with_indifferent_access_benchmark.rb | |
| # Calculating ------------------------------------- | |
| # Common Hash access 48.481k i/100ms | |
| # HashWithIndifferentAccess#fetch Symbol | |
| # 39.126k i/100ms | |
| # HashWithIndifferentAccess#fetch String | |
| # 37.910k i/100ms | |
| # HashWithIndifferentAccess #[] Symbol | |
| # 33.985k i/100ms | |
| # HashWithIndifferentAccess #[] String | |
| # 42.670k i/100ms | |
| # ------------------------------------------------- | |
| # Common Hash access 5.650M (±10.1%) i/s - 27.877M | |
| # HashWithIndifferentAccess#fetch Symbol | |
| # 1.953M (± 8.5%) i/s - 9.703M | |
| # HashWithIndifferentAccess#fetch String | |
| # 1.985M (± 7.8%) i/s - 9.857M | |
| # HashWithIndifferentAccess #[] Symbol | |
| # 1.410M (± 7.2%) i/s - 7.035M | |
| # HashWithIndifferentAccess #[] String | |
| # 3.704M (±10.0%) i/s - 18.305M | |
| # | |
| # Comparison: | |
| # Common Hash access: 5649613.0 i/s | |
| # HashWithIndifferentAccess #[] String: 3703535.0 i/s - 1.53x slower | |
| # HashWithIndifferentAccess#fetch String: 1984536.9 i/s - 2.85x slower | |
| # HashWithIndifferentAccess#fetch Symbol: 1953020.8 i/s - 2.89x slower | |
| # HashWithIndifferentAccess #[] Symbol: 1410364.2 i/s - 4.01x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment