Skip to content

Instantly share code, notes, and snippets.

@rosenfeld
Last active December 12, 2015 06:58
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save rosenfeld/4732737 to your computer and use it in GitHub Desktop.
trade-offs between hashes and HashWithIndifferentAccess
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
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