Skip to content

Instantly share code, notes, and snippets.

@vasilakisfil
Last active December 21, 2017 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vasilakisfil/845d2d9258cee99bb293c13a9c1ffd58 to your computer and use it in GitHub Desktop.
Save vasilakisfil/845d2d9258cee99bb293c13a9c1ffd58 to your computer and use it in GitHub Desktop.
Decorator strategies battletested. Original script: https://gist.github.com/rbishop/7555357
#ENV: Ruby 2.4.1, a i7-6700HQ CPU, 16GB RAM
require 'benchmark'
require 'delegate'
require 'forwardable'
class Person
def initialize(name)
@name = name
end
def name
@name
end
end
class PersonDelegator < SimpleDelegator
def initialize(person)
super(person)
end
end
class PersonForwarder
extend Forwardable
def_delegator :@person, :name
def initialize(person)
@person = person
end
end
class PersonMissing
def method_missing(method_name)
if @person.respond_to?(method_name)
@person.send(method_name)
else
super
end
end
def initialize(person)
@person = person
end
end
class SubPerson < Person
end
bob = Person.new('Bob')
decorated_bob = PersonDelegator.new(bob)
forwarded_bob = PersonForwarder.new(bob)
missing_bob = PersonMissing.new(bob)
sub_person = SubPerson.new(bob)
Benchmark.bmbm do |bm|
bm.report('Sending message directly') do
1_000_000.times do
bob.name
end
end
bm.report 'Sending message through SimpleDelegator' do
1_000_000.times do
decorated_bob.name
end
end
bm.report 'Forwarding message using Forwardable' do
1_000_000.times do
forwarded_bob.name
end
end
bm.report 'Sending message using method_missing' do
1_000_000.times do
missing_bob.name
end
end
bm.report 'Sending message using subclassing' do
1_000_000.times do
sub_person.name
end
end
end
#Rehearsal ---------------------------------------------------------------------------
#Sending message directly 0.050000 0.000000 0.050000 ( 0.055301)
#Sending message through SimpleDelegator 0.280000 0.000000 0.280000 ( 0.280395)
#Forwarding message using Forwardable 0.150000 0.000000 0.150000 ( 0.150432)
#Sending message using method_missing 0.160000 0.000000 0.160000 ( 0.157218)
#Sending message using subclassing 0.050000 0.000000 0.050000 ( 0.052206)
#------------------------------------------------------------------ total: 0.690000sec
#
# user system total real
#Sending message directly 0.050000 0.000000 0.050000 ( 0.050754)
#Sending message through SimpleDelegator 0.280000 0.000000 0.280000 ( 0.279871)
#Forwarding message using Forwardable 0.160000 0.000000 0.160000 ( 0.152889)
#Sending message using method_missing 0.150000 0.000000 0.150000 ( 0.152737)
#Sending message using subclassing 0.050000 0.000000 0.050000 ( 0.051002)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment