Skip to content

Instantly share code, notes, and snippets.

@dvandersluis
Last active May 25, 2017 15:35
Show Gist options
  • Save dvandersluis/5132a5d0dd5e01bba0546597c5e81da6 to your computer and use it in GitHub Desktop.
Save dvandersluis/5132a5d0dd5e01bba0546597c5e81da6 to your computer and use it in GitHub Desktop.
Possible solution to the alias puzzle, with benchmarks
require 'active_support/core_ext/array/wrap'
module OverridableAlias
def overridable_alias(name, aliases:, &block)
define_method(name) do
method = method(name)
if method.super_method
send(name) # faster than method.call
else
yield
end
end
Array.wrap(aliases).each do |a|
alias_method a, name
end
end
end
class A
extend OverridableAlias
overridable_alias(:foo, aliases: [:bar, :baz]) do
'hello'
end
end
class B < A
def foo
'bye'
end
end
class C < A
end
class D
def foo
'hello'
end
alias_method :bar, :foo
end
class E < D
def foo
'bye'
end
alias_method :bar, :foo
end
require 'benchmark/ips'
a = A.new
b = B.new
c = C.new
d = D.new
e = E.new
Benchmark.ips do |x|
x.report("a.bar") { a.bar }
x.report("b.bar") { b.bar }
x.report("c.bar") { c.bar }
x.report("d.bar") { d.bar }
x.report("e.bar") { e.bar }
x.compare!
end
@dvandersluis
Copy link
Author

dvandersluis commented May 25, 2017

Warming up --------------------------------------
               a.bar   122.867k i/100ms
               b.bar    89.096k i/100ms
               c.bar   122.991k i/100ms
               d.bar   248.042k i/100ms
               e.bar   248.293k i/100ms
Calculating -------------------------------------
               a.bar      2.029M (±10.3%) i/s -     10.075M in   5.028884s
               b.bar      1.325M (± 5.1%) i/s -      6.682M in   5.055119s
               c.bar      2.067M (± 5.1%) i/s -     10.331M in   5.013844s
               d.bar      8.198M (± 5.1%) i/s -     40.927M in   5.005289s
               e.bar      8.521M (± 6.7%) i/s -     42.458M in   5.007338s

Comparison:
               e.bar:  8520938.6 i/s
               d.bar:  8198143.6 i/s - same-ish: difference falls within error
               c.bar:  2066677.3 i/s - 4.12x  slower
               a.bar:  2028980.8 i/s - 4.20x  slower
               b.bar:  1325251.7 i/s - 6.43x  slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment