Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save jrunning/adac126130b27582b096 to your computer and use it in GitHub Desktop.

Select an option

Save jrunning/adac126130b27582b096 to your computer and use it in GitHub Desktop.
require "benchmark/ips"
class Test
def initialize(test_value)
@test_value = test_value
assert_equal(self_merge_with_block(@test_value), map_then_hash(@test_value))
end
def self_merge_with_block(hsh)
hsh.merge(hsh) {|_, val| val * 2 }
end
def map_then_hash(hsh)
Hash[ hsh.map {|key, val| [ key, val * 2 ] } ]
end
def perform
Benchmark.ips do |x|
x.report("self_merge_with_block") { self_merge_with_block(@test_value) }
x.report("map_then_hash") { map_then_hash(@test_value) }
x.compare!
end
end
def assert_equal(a, b)
return if a == b
raise "Expected arguments to be equal"
end
end
Test.new(Hash[ ('aa'..'dv').zip(0..99) ]).perform
Calculating -------------------------------------
self_merge_with_block
1965 i/100ms
map_then_hash 2313 i/100ms
-------------------------------------------------
self_merge_with_block
21586.4 (±26.3%) i/s - 98250 in 5.020320s
map_then_hash 23468.8 (±2.2%) i/s - 117963 in 5.028741s
Comparison:
map_then_hash: 23468.8 i/s
self_merge_with_block: 21586.4 i/s - 1.09x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment