Skip to content

Instantly share code, notes, and snippets.

@ffloyd
Last active August 29, 2015 14:06
Show Gist options
  • Save ffloyd/184c3a0d8d4ce9bc6d6f to your computer and use it in GitHub Desktop.
Save ffloyd/184c3a0d8d4ce9bc6d6f to your computer and use it in GitHub Desktop.
double_method
require 'benchmark'
require 'active_support'
module Hello
extend ActiveSupport::Concern
BENCH_ITERS = 1_000_000
included do
double_method :hello_double, :hello
alias hello_alias hello
alias_method :hello_alias_method, :hello
define_method :hello_define_method, instance_method(:hello)
end
module ClassMethods
def double_method(double_name, orig_name) # <----------------- all this gist about this guy
self.class_eval <<-RUBY
def #{double_name}(*args, &block)
#{orig_name}(*args, &block)
end
RUBY
end
end
def hello
'hello world'
end
def test
puts "Test for #{self.class.to_s}"
puts " alias: #{hello_alias}"
puts " alias_method: #{hello_alias_method}"
puts " define_method: #{hello_define_method}"
puts " double_method: #{hello_double}"
self
end
def benchmark
puts "Benchmark for #{self.class.to_s}"
bench_orig = Benchmark.measure { BENCH_ITERS.times { hello } }
bench_alias = Benchmark.measure { BENCH_ITERS.times { hello_alias } }
bench_alias_method = Benchmark.measure { BENCH_ITERS.times { hello_alias_method } }
bench_define_method = Benchmark.measure { BENCH_ITERS.times { hello_define_method } }
bench_double = Benchmark.measure { BENCH_ITERS.times { hello_double } }
puts " original: #{bench_orig}"
puts " alias: #{bench_alias}"
puts " alias_method: #{bench_alias_method}"
puts " define_method: #{bench_define_method}"
puts " double_method: #{bench_double}"
self
end
end
class A
include Hello
end
class B < A
include Hello
def hello
'overridden hello'
end
end
A.new.test.benchmark
B.new.test.benchmark
# Example output:
#
# Test for A
# alias: hello world
# alias_method: hello world
# define_method: hello world
# double_method: hello world
# Benchmark for A
# original: 0.150000 0.000000 0.150000 ( 0.144486)
# alias: 0.140000 0.000000 0.140000 ( 0.144081)
# alias_method: 0.140000 0.000000 0.140000 ( 0.141664)
# define_method: 0.150000 0.000000 0.150000 ( 0.141005)
# double_method: 0.260000 0.000000 0.260000 ( 0.268172)
# Test for B
# alias: hello world
# alias_method: hello world
# define_method: hello world
# double_method: overridden hello
# Benchmark for B
# original: 0.150000 0.000000 0.150000 ( 0.145959)
# alias: 0.140000 0.000000 0.140000 ( 0.143349)
# alias_method: 0.150000 0.000000 0.150000 ( 0.147040)
# define_method: 0.150000 0.000000 0.150000 ( 0.146973)
# double_method: 0.260000 0.000000 0.260000 ( 0.262837)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment