Skip to content

Instantly share code, notes, and snippets.

@pingzh
Forked from EmmanuelOga/callback.rb
Last active May 24, 2016 01:49
Show Gist options
  • Save pingzh/661091fbfff5cd1fefe7 to your computer and use it in GitHub Desktop.
Save pingzh/661091fbfff5cd1fefe7 to your computer and use it in GitHub Desktop.
callback test.
require 'benchmark'
class Proc
def slow_callback(callable, *args)
self === Class.new do
method_name = callable.to_sym
define_method(method_name) { |&block| block.nil? ? true : block.call(*args) }
define_method("#{method_name}?") { true }
def method_missing(method_name, *args, &block) false; end
end.new
end
end
def slow_tweet(&block)
block.slow_callback :failure, "FAIL"
end
ProcCallback = Struct.new(:called, :args) do
def method_missing(name, *)
name == :"#{called}?" || (name == called && block_given? && yield(*args))
end
end
def tweet
yield ProcCallback.new(:failure, "FAIL")
end
TIMES = 10_000
Benchmark.bmbm do |rep|
rep.report("slow") do
TIMES.times do
slow_tweet do |cbk|
cbk.success { }
cbk.failure { |status| }
cbk.success?
cbk.failure?
end
end
end
rep.report("fast") do
TIMES.times do
tweet do |cbk|
cbk.success { }
cbk.failure { |status| }
cbk.success?
cbk.failure?
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment