Skip to content
This repository
tag: v2.14.3
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 82 lines (70 sloc) 1.331 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
require 'benchmark'

n = 1_000_000

puts "each sample runs #{n} times"
puts

class Foo
  define_method :foo do
    @foo
  end

  attr_reader :bar

  def initialize
    @foo = 'foo'
    @bar = 'bar'
    @baz = 'baz'
  end

  def baz
    @baz
  end
end

foo = Foo.new

puts "define_method"
Benchmark.benchmark do |bm|
  3.times do
    bm.report do
      n.times do
        foo.foo
      end
    end
  end
end

puts
puts "attr_reader"
Benchmark.benchmark do |bm|
  3.times do
    bm.report do
      n.times do
        foo.bar
      end
    end
  end
end

puts
puts "def"
Benchmark.benchmark do |bm|
  3.times do
    bm.report do
      n.times do
        foo.baz
      end
    end
  end
end

# $ ruby -v
# ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-darwin11.0.0]
# $ ruby benchmarks/define_method_v_attr_reader_v_def.rb
# each sample runs 1000000 times
#
# define_method
# 0.250000 0.000000 0.250000 ( 0.251552)
# 0.250000 0.000000 0.250000 ( 0.261506)
# 0.250000 0.000000 0.250000 ( 0.247398)
#
# attr_reader
# 0.140000 0.000000 0.140000 ( 0.141782)
# 0.140000 0.000000 0.140000 ( 0.142411)
# 0.140000 0.000000 0.140000 ( 0.145876)
#
# def
# 0.160000 0.000000 0.160000 ( 0.153261)
# 0.150000 0.000000 0.150000 ( 0.158096)
# 0.150000 0.000000 0.150000 ( 0.149472)
Something went wrong with that request. Please try again.