Skip to content

Instantly share code, notes, and snippets.

@binarycleric
Created April 3, 2014 17:07
Show Gist options
  • Save binarycleric/9958595 to your computer and use it in GitHub Desktop.
Save binarycleric/9958595 to your computer and use it in GitHub Desktop.
Using a single object vs. creating a new one each time. Pretty basic Ruby stuff but I still see this anti-pattern all over the place.
class ClassThatDoesStuff
def some_method
"You're winner!"
end
end
require 'benchmark'
puts "Using a single instance : 5000 times"
Benchmark.benchmark do |x|
x.report do
doer = ClassThatDoesStuff.new
5000.times{|n| doer.some_method}
end
end
puts "\n"
puts "Creating an instance each time : 5000 times"
Benchmark.benchmark do |x|
x.report do
5000.times{|n| ClassThatDoesStuff.new.some_method}
end
end
puts "\n\n"
@binarycleric
Copy link
Author

jon:~/src/candy (ruby-1.9.3-p484)
 $ ruby ruby_object_test.rb
Using a single instance : 5000 times
    0.000000   0.000000   0.000000 (  0.000540)

Creating an instance each time : 5000 times
    0.000000   0.000000   0.000000 (  0.001040)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment