Skip to content

Instantly share code, notes, and snippets.

@arthurnn
Created July 19, 2013 01:57
Show Gist options
  • Save arthurnn/6034518 to your computer and use it in GitHub Desktop.
Save arthurnn/6034518 to your computer and use it in GitHub Desktop.
require 'benchmark'
class Coffee
def cost
2
end
def origin
"Colombia"
end
end
module PORO
class Milk
def initialize(component)
@component = component
end
def cost
@component.cost + 0.4
end
end
class Sugar
def initialize(component)
@component = component
end
def cost
@component.cost + 0.2
end
end
end
module Decorator
def initialize(component)
@component = component
end
def method_missing(meth, *args)
if @component.respond_to?(meth)
@component.send(meth, *args)
else
super
end
end
def respond_to?(meth)
@component.respond_to?(meth)
end
end
module MM
class Milk
include Decorator
def cost
@component.cost + 0.4
end
end
class Sugar
include Decorator
def cost
@component.cost + 0.2
end
end
end
module Inher
class CoffeeWithSugar < Coffee
def cost
super + 0.2
end
end
class CoffeeWithSugarAndMilk < CoffeeWithSugar
def cost
super + 0.4
end
end
end
iterations = 1_000_000
coffee = Coffee.new
poro = PORO::Sugar.new(PORO::Milk.new(coffee))
mm = MM::Sugar.new(MM::Milk.new(coffee))
inher = Inher::CoffeeWithSugarAndMilk.new
Benchmark.bm do |bm|
bm.report("PORO") do
iterations.times do
poro.cost
end
end
bm.report("MM ") do
iterations.times do
mm.cost
end
end
bm.report("inhe") do
iterations.times do
inher.cost
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment