Skip to content

Instantly share code, notes, and snippets.

@jonmagic
Forked from rbishop/decorator_perf.rb
Last active March 25, 2021 01:51
Show Gist options
  • Save jonmagic/781539348f490384a2f442e9a8b7b116 to your computer and use it in GitHub Desktop.
Save jonmagic/781539348f490384a2f442e9a8b7b116 to your computer and use it in GitHub Desktop.
require "benchmark"
require "delegate"
require "forwardable"
class Person
def initialize(name, ip)
@name = name
@ip = ip
end
def name
@name
end
def ip
@ip
end
def to_hash
{
name: name,
ip: ip,
}
end
end
class PersonDelegator < SimpleDelegator
def initialize(person)
super(person)
end
end
class PersonForwarder
extend Forwardable
def_delegator :@person, :name
def_delegator :@person, :ip
def initialize(person)
@person = person
end
end
class PersonCopy
def initialize(person)
attributes = person.to_hash
person.public_methods(false).each do |method_name|
define_singleton_method(method_name) { attributes[method_name] }
end
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
bob = Person.new("Bob", "1.2.3.4")
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
PersonDelegator.new(bob).name
end
end
bm.report "Forwarding message using Forwardable" do
1_000_000.times do
PersonForwarder.new(bob).name
end
end
bm.report "Forwarding message using define_singleton_method" do
1_000_000.times do
PersonCopy.new(bob).name
end
end
bm.report "Sending message using method_missing" do
1_000_000.times do
PersonMissing.new(bob).name
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment