Posted By


esad on 11/29/07

Tagged


Statistics


Viewed 69 times
Favorited by 1 user(s)

Benchmarking Object#ergo


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require 'benchmark'
  2.  
  3. # The original implementation by Daniel DeLorme
  4. # http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/256662
  5.  
  6. class NilClass
  7. def ergo
  8. @blackhole ||= Object.new.instance_eval do
  9. class << self
  10. for m in public_instance_methods
  11. undef_method(m.to_sym) unless m =~ /^__.*__$/
  12. end
  13. end
  14. def method_missing(*args); nil; end
  15. self
  16. end
  17. @blackhole unless block_given?
  18. end
  19. end
  20.  
  21. class Object
  22. def ergo
  23. if block_given?
  24. yield(self)
  25. else
  26. self
  27. end
  28. end
  29. end
  30.  
  31. a,b = [1,2,3], nil
  32. n = 100_000
  33.  
  34. Benchmark.bm(15) do |x|
  35. x.report("Original") do
  36. n.times { a.ergo[0]; b.ergo[0] }
  37. end
  38.  
  39. # Turn to facets implementation
  40. require 'rubygems'
  41. require 'facets/nilclass/ergo'
  42.  
  43. x.report("Facets") do
  44. n.times { a.ergo[0]; b.ergo[0] }
  45. end
  46.  
  47. x.report("Logic operators") do
  48. n.times { a && a[0]; b && b[0] }
  49. end
  50. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.