Skip to content

Instantly share code, notes, and snippets.

@araslanov-e
Last active March 17, 2019 09:47
Show Gist options
  • Save araslanov-e/51505c55e4495bcea202c463095efc53 to your computer and use it in GitHub Desktop.
Save araslanov-e/51505c55e4495bcea202c463095efc53 to your computer and use it in GitHub Desktop.
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