Benchmark callable vs proc as event handlers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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