trade-offs between hashes and HashWithIndifferentAccess
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' | |
require 'active_support/hash_with_indifferent_access' | |
Benchmark.bmbm do |x| | |
l1 = []; l2 = [] | |
# writing: | |
# simulate objects returned by Sequel queries: | |
x.report('creating array or regular hashes'){10_000.times{ l1 << { id: 1, name: 'column value' } }} | |
x.report('creating array or proposed hashes'){10_000.times{ l2 << HashWithIndifferentAccess.new({ id: 1, name: 'column value' }) }} | |
x.report('converting existing hashes to behave like HWIA'){l2 = l1.map{|h| HashWithIndifferentAccess.new(h) }} | |
# reading: | |
x.report('manual conversion'){l1.map{|h| {'id' => h[:id], 'name' => h[:name]} }} | |
x.report('using HashWithIndifferentAccess approach'){ l2 } # no additional action required | |
end |
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
ruby bm.rb | |
Rehearsal ---------------------------------------------------------------------------------- | |
creating array or regular hashes 0.010000 0.000000 0.010000 ( 0.008780) | |
creating array or proposed hashes 0.050000 0.010000 0.060000 ( 0.051333) | |
converting existing hashes to behave like HWIA 0.040000 0.000000 0.040000 ( 0.041100) | |
manual conversion 0.020000 0.000000 0.020000 ( 0.022305) | |
using HashWithIndifferentAccess approach 0.000000 0.000000 0.000000 ( 0.000002) | |
------------------------------------------------------------------------- total: 0.130000sec | |
user system total real | |
creating array or regular hashes 0.010000 0.000000 0.010000 ( 0.006545) | |
creating array or proposed hashes 0.030000 0.000000 0.030000 ( 0.034010) | |
converting existing hashes to behave like HWIA 0.090000 0.000000 0.090000 ( 0.083644) | |
manual conversion 0.030000 0.000000 0.030000 ( 0.026515) | |
using HashWithIndifferentAccess approach 0.000000 0.000000 0.000000 ( 0.000004) | |
NOTE: since we're also creating regular hashes for the second report, we should discount | |
its time if we consider that the normal hash syntax would create HWIA: | |
0.034 - 0.007 =~ 0.027 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment