jodosha (owner)

Revisions

gist: 163274 Download_button fork
public
Public Clone URL: git://gist.github.com/163274.git
Embed All Files: show embed
enumerable_else.rb #
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
require "benchmark"
require "rubygems"
require "activesupport"
 
module Enumerable
  def else(&block)
    self.respond_to?('empty?') && self.empty? ? yield : self
  end
 
  def else_try(&block)
    self.try(:empty?) ? yield : self
  end
 
  def else_try_with_no_block
    self.try(:empty?) ? yield : self
  end
 
  def else_any
    not any? ? yield : self
  end
end
 
TIMES = 5_000_000
EMPTY_ARRAY = []
FILLED_ARRAY = [1]
 
Benchmark.bm(40) do |b|
  b.report("empty array with else") do
    TIMES.times do |i|
      EMPTY_ARRAY.each do |element|
      end.else do
      end
    end
  end
 
  b.report("empty array with else_try") do
    TIMES.times do |i|
      EMPTY_ARRAY.each do |element|
      end.else_try do
      end
    end
  end
 
  b.report("empty array with else_try_with_no_block") do
    TIMES.times do |i|
      EMPTY_ARRAY.each do |element|
      end.else_try_with_no_block do
      end
    end
  end
 
  b.report("empty array with else_any") do
    TIMES.times do |i|
      EMPTY_ARRAY.each do |element|
      end.else_any do
      end
    end
  end
 
  b.report("filled array with else") do
    TIMES.times do |i|
      FILLED_ARRAY.each do |element|
      end.else do
      end
    end
  end
 
  b.report("filled array with else_try") do
    TIMES.times do |i|
      FILLED_ARRAY.each do |element|
      end.else_try do
      end
    end
  end
 
  b.report("filled array with else_try_with_no_block") do
    TIMES.times do |i|
      FILLED_ARRAY.each do |element|
      end.else_try_with_no_block do
      end
    end
  end
 
  b.report("filled array with else_any") do
    TIMES.times do |i|
      FILLED_ARRAY.each do |element|
      end.else_any do
      end
    end
  end
end
 
__END__
 
                                              user     system      total        real
empty array with else                    17.920000   0.070000  17.990000 ( 18.145576)
empty array with else_try                16.880000   0.050000  16.930000 ( 17.086479)
empty array with else_try_with_no_block   4.650000   0.020000   4.670000 (  4.694035)
empty array with else_any                 4.010000   0.010000   4.020000 (  4.045465)
filled array with else                   16.470000   0.050000  16.520000 ( 16.674411)
filled array with else_try               15.370000   0.060000  15.430000 ( 15.563179)
filled array with else_try_with_no_block  4.600000   0.010000   4.610000 (  4.639092)
filled array with else_any                7.710000   0.020000   7.730000 (  7.783507)