Skip to content

Instantly share code, notes, and snippets.

@bricker
Created July 9, 2012 18:28
Show Gist options
  • Save bricker/3078055 to your computer and use it in GitHub Desktop.
Save bricker/3078055 to your computer and use it in GitHub Desktop.
Benchmark for Class method vs. instance method
# The verdict: Doesn't matter which one.
class MethodTesterObject
class << self
def perform(instances)
instances.each { |obj| obj.action }
end
end
attr_accessor :value
def initialize
self.value = rand(36**8).to_s(36)
end
def perform
self.action
end
def action
1000.times { self.value * 100 }
end
end
class MethodTester
def self.run
instances = []
1000.times { instances.push MethodTesterObject.new }
puts "Running instance method."
puts Benchmark.measure { instances.each { |i| i.perform } }
puts "Running class method."
puts Benchmark.measure { MethodTesterObject.perform(instances) }
end
end
1.9.3p0 :099 > MethodTester.run
Running instance method.
1.210000 0.180000 1.390000 ( 1.385852)
Running class method.
1.200000 0.160000 1.360000 ( 1.358509)
=> nil
1.9.3p0 :100 > MethodTester.run
Running instance method.
1.150000 0.140000 1.290000 ( 1.287323)
Running class method.
1.140000 0.140000 1.280000 ( 1.282318)
=> nil
1.9.3p0 :101 > MethodTester.run
Running instance method.
1.150000 0.140000 1.290000 ( 1.287659)
Running class method.
1.170000 0.150000 1.320000 ( 1.316425)
=> nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment