public
Last active

trade-offs between hashes and HashWithIndifferentAccess

  • Download Gist
bm.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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
report.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.