Skip to content

Instantly share code, notes, and snippets.

@cameronbarker
Last active December 8, 2022 00:44
Show Gist options
  • Save cameronbarker/9dd083ab64f6dd9233879721eb7e7137 to your computer and use it in GitHub Desktop.
Save cameronbarker/9dd083ab64f6dd9233879721eb7e7137 to your computer and use it in GitHub Desktop.
Class vs. Method Self.Method vs Method Class << Self Method vs Method Extend Self
require 'benchmark/ips'
# gem install benchmark-ips -v 2.7.2
class TestClass
def echo(value)
value
end
end
module TestModule
def self.echo(value)
value
end
end
module TestModuleSelf
class << self
def echo(value)
value
end
end
end
module TestModuleExtendSelf
extend self
def echo(value)
value
end
end
val = :value
Benchmark.ips do |x|
x.report("klass") { TestClass.new.echo(val) }
x.report("method") { TestModule.echo(val) }
x.report("method_self") { TestModuleSelf.echo(val) }
x.report("extend") { TestModuleExtendSelf.echo(val) }
end
# Warming up --------------------------------------
# klass 540.240k i/100ms
# method 1.169M i/100ms
# method_self 1.254M i/100ms
# extend 1.196M i/100ms
# Calculating -------------------------------------
# klass 5.243M (± 5.6%) i/s - 26.472M in 5.067397s
# method 12.518M (± 2.2%) i/s - 63.110M in 5.044083s
# method_self 12.516M (± 1.0%) i/s - 62.690M in 5.009332s
# extend 12.092M (± 4.9%) i/s - 60.987M in 5.060271s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment