Skip to content

Instantly share code, notes, and snippets.

@casperisfine
Last active February 5, 2022 10:14
Show Gist options
  • Save casperisfine/1c46f05cccfa945cd156f445f0d3d6fa to your computer and use it in GitHub Desktop.
Save casperisfine/1c46f05cccfa945cd156f445f0d3d6fa to your computer and use it in GitHub Desktop.
require "benchmark/ips"
require "active_support/all"
class Hash
def refined_symbolize_keys
transform_keys { |key| key.to_sym rescue key }
end
end
module HashRefinements
refine Hash do
def refined_symbolize_keys
raise "never called"
end
end
end
HASH = {foo: 1, bar: 2, baz: 3}
Benchmark.ips do |x|
x.report('original') { HASH.symbolize_keys }
x.report('refined') { HASH.refined_symbolize_keys }
x.compare!
end
class Foo
def original
end
def refined
end
end
module FooRefinements
refine Foo do
def refined
raise "never called"
end
end
end
FOO = Foo.new
Benchmark.ips do |x|
x.report('original') { FOO.original }
x.report('refined') { FOO.refined }
x.compare!
end
$ ruby -v
ruby 3.0.2p107 (2021-07-07 revision 0db68f0233) [x86_64-darwin20]
$ ruby /tmp/refinements.rb
Warming up --------------------------------------
original 45.445k i/100ms
refined 40.602k i/100ms
Calculating -------------------------------------
original 456.533k (± 0.8%) i/s - 2.318M in 5.077034s
refined 410.539k (± 0.7%) i/s - 2.071M in 5.044141s
Comparison:
original: 456533.1 i/s
refined: 410539.2 i/s - 1.11x (± 0.00) slower
Warming up --------------------------------------
original 258.910k i/100ms
refined 182.152k i/100ms
Calculating -------------------------------------
original 2.595M (± 0.6%) i/s - 13.204M in 5.088884s
refined 1.816M (± 0.5%) i/s - 9.108M in 5.015045s
Comparison:
original: 2594845.6 i/s
refined: 1816097.0 i/s - 1.43x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment