Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created September 5, 2018 03:00
Show Gist options
  • Save jgaskins/e493f7f87f05e9c96cfcb289d0c0fa12 to your computer and use it in GitHub Desktop.
Save jgaskins/e493f7f87f05e9c96cfcb289d0c0fa12 to your computer and use it in GitHub Desktop.
Benchmark callable vs proc as event handlers
class EventHandler
def call event
end
end
class Eventable
def initialize
@events = Hash.new { |h, k| h[k] = [] }
end
def on event_name, handler=nil, &block
@events[event_name] << (handler || block)
end
def trigger event_name, event
@events[event_name].each { |handler| handler.call event }
end
end
callables = Eventable.new
procs = Eventable.new
mix = Eventable.new
2.times { callables.on(:foo, EventHandler.new) }
2.times { procs.on(:foo) {} }
mix.on(:foo, EventHandler.new)
mix.on(:foo) {}
Benchmark.ips do |x|
x.report('callables') { callables.trigger :foo, 1 }
x.report('procs') { procs.trigger :foo, 1 }
x.report('mix') { mix.trigger :foo, 1 }
x.compare!
end
Comparison:
callables: 3788280.0 i/s
procs: 2606729.7 i/s - 1.45x slower
mix: 2446583.1 i/s - 1.55x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment