Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby: class methods vs. instance methods
require "benchmark/memory"
class A
def self.class_method
puts 'hello'
end
def instance_method
puts 'hello'
end
end
Benchmark.memory do |x|
x.report("class_method") { A.class_method }
x.report("instance_method") { A.new.instance_method }
x.compare!
end
#Calculating -------------------------------------
#hello
# class_method 40.000 memsize ( 0.000 retained)
# 1.000 objects ( 0.000 retained)
# 1.000 strings ( 0.000 retained)
#hello
# instance_method 80.000 memsize ( 0.000 retained)
# 2.000 objects ( 0.000 retained)
# 1.000 strings ( 0.000 retained)
#
#Comparison:
# class_method: 40 allocated
# instance_method: 80 allocated - 2.00x more
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment