Skip to content

Instantly share code, notes, and snippets.

@MSch
Created February 8, 2012 02:11
Show Gist options
  • Save MSch/1764432 to your computer and use it in GitHub Desktop.
Save MSch/1764432 to your computer and use it in GitHub Desktop.
require 'benchmark'
# The original implementation by Daniel DeLorme
# http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/256662
class NilClass
def ergo
@blackhole ||= Object.new.instance_eval do
class << self
for m in public_instance_methods
undef_method(m.to_sym) unless m == :object_id || m =~ /^__.*__$/
end
end
def method_missing(*args); nil; end
self
end
@blackhole unless block_given?
end
end
class Object
def ergo
if block_given?
yield(self)
else
self
end
end
end
a,b = [1,2,3], nil
n = 100_000
class Object
def try(*a, &b)
if a.empty? && block_given?
yield self
else
__send__(*a, &b)
end
end
end
class NilClass
def try(*args)
nil
end
end
Benchmark.bm(150) do |x|
x.report("Original") do
n.times { a.ergo[0]; b.ergo[0] }
end
# Turn to facets implementation
require 'rubygems'
require 'facets/nilclass/ergo'
x.report("Facets") do
n.times { a.ergo[0]; b.ergo[0] }
end
x.report("Logic operators") do
n.times { a && a[0]; b && b[0] }
end
x.report("try") do
n.times { a.try(:[], 0) ; b.try(:[], 0) }
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment