Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save tsara27/66b2f3f123e651a9e56073ddf8937991 to your computer and use it in GitHub Desktop.
Save tsara27/66b2f3f123e651a9e56073ddf8937991 to your computer and use it in GitHub Desktop.
Extend + method call VS method call
require 'benchmark'
module Foo
def bar
end
def baz
end
end
module Baz
def foo
end
def bar
end
end
module Caz
100.times do |i|
define_method "meth_#{i}" do
a = 1
end
end
end
class User
include Foo
include Baz
include Caz
end
class BlankUser
end
u = User.new
bu = BlankUser.new
# Let's benchmarks the *worst* case
n = 1_000_000
Benchmark.bmbm do |x|
x.report("include") { n.times { User.new.bar } }
x.report("extend") { n.times { BlankUser.new.extend(Foo).bar } }
end
# Ruby1.8
# user system total real
# include 1.390000 0.300000 1.690000 ( 1.694982)
# extend 12.130000 0.360000 12.490000 ( 12.490052)
# Profiler (install ruby-prof gem)
# CLASS
# %self total self wait child calls name
# 40.65 8.88 3.61 0.00 5.27 1 Integer#times (ruby_runtime:0}
# 26.46 4.75 2.35 0.00 2.40 1000000 Class#new (ruby_runtime:0}
# 13.96 1.24 1.24 0.00 0.00 1000000 Object#initialize (ruby_runtime:0}
# 13.06 1.16 1.16 0.00 0.00 1000000 <Class::Object>#allocate (ruby_runtime:0}
# 5.86 0.52 0.52 0.00 0.00 1000000 Baz#bar (perf.rb:18}
# 0.00 8.88 0.00 0.00 8.88 1 Global#[No method] (perf.rb:46}
# SINGLETON
# %self total self wait child calls name
# 40.08 26.00 10.42 0.00 15.58 1 Integer#times (ruby_runtime:0}
# 21.42 5.57 5.57 0.00 0.00 1000000 Module#extend_object (ruby_runtime:0}
# 10.81 9.71 2.81 0.00 6.90 1000000 Kernel#extend (ruby_runtime:0}
# 10.15 5.21 2.64 0.00 2.57 1000000 Class#new (ruby_runtime:0}
# 5.38 1.40 1.40 0.00 0.00 1000000 <Class::Object>#allocate (ruby_runtime:0}
# 5.12 1.33 1.33 0.00 0.00 1000000 Module#extended (ruby_runtime:0}
# 4.50 1.17 1.17 0.00 0.00 1000000 Object#initialize (ruby_runtime:0}
# 2.54 0.66 0.66 0.00 0.00 1000000 Foo#bar (perf.rb:6}
# 0.00 26.00 0.00 0.00 26.00 1 Global#[No method] (perf.rb:51}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment