Skip to content

Instantly share code, notes, and snippets.

@EmmanuelOga
Created December 1, 2011 15:54
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save EmmanuelOga/1417762 to your computer and use it in GitHub Desktop.
Save EmmanuelOga/1417762 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