Instantly share code, notes, and snippets.

Embed
What would you like to do?
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