Created
September 5, 2018 03:00
-
-
Save jgaskins/e493f7f87f05e9c96cfcb289d0c0fa12 to your computer and use it in GitHub Desktop.
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