Skip to content

Instantly share code, notes, and snippets.

@paul
Created May 16, 2016 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paul/3d569539514baf5ea2047cf2ce5627ac to your computer and use it in GitHub Desktop.
Save paul/3d569539514baf5ea2047cf2ce5627ac to your computer and use it in GitHub Desktop.
require "benchmark/ips"
require "active_support/callbacks"
class NormalMethod
def before
:before
end
def perform
before
:perform
end
end
class NaiveMethod
def initialize
@before_callbacks = []
@before_callbacks << lambda { :before }
end
def perform
@before_callbacks.each { |cb| cb.call }
:perform
end
end
class CallbackMethod
include ActiveSupport::Callbacks
define_callbacks :perform
set_callback :perform, :before do
:before
end
def perform
run_callbacks :perform do
:perform
end
end
end
Benchmark.ips do |x|
x.report("normal w/ init") { NormalMethod.new.perform }
x.report("naive w/ init") { NaiveMethod.new.perform }
x.report("as::cb w/ init") { CallbackMethod.new.perform }
NORMAL = NormalMethod.new
NAIEVE = NaiveMethod.new
CALLBACK = CallbackMethod.new
x.report("normal w/o init") { NORMAL.perform }
x.report("naive w/o init") { NAIEVE.perform }
x.report("as::cb w/o init") { CALLBACK.perform }
end
Warming up --------------------------------------
normal w/ init 147.639k i/100ms
naive w/ init 53.250k i/100ms
as::cb w/ init 10.227k i/100ms
normal w/o init 175.545k i/100ms
naive w/o init 149.439k i/100ms
as::cb w/o init 12.302k i/100ms
Calculating -------------------------------------
normal w/ init 3.172M (± 9.2%) i/s - 15.797M in 5.036397s
naive w/ init 803.257k (±21.8%) i/s - 3.834M in 5.041431s
as::cb w/ init 114.992k (±13.5%) i/s - 562.485k in 5.011706s
normal w/o init 4.763M (± 4.6%) i/s - 23.874M in 5.022535s
naive w/o init 2.838M (± 4.0%) i/s - 14.197M in 5.010108s
as::cb w/o init 140.246k (±11.3%) i/s - 701.214k in 5.070732s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment