mynyml / every

Symbol#to_proc's hot cousin. Simple and elegant alternative to using &:method with enumerables.

This URL has Read+Write access

every / benchmarks.rb
100644 33 lines (28 sloc) 0.89 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
#!/usr/lib/env ruby
 
require 'pathname'
require 'benchmark'
root = Pathname(__FILE__).dirname
require root.join('lib/every.rb')
 
unless defined?(:a.to_proc)
  class Symbol
    def to_proc() proc { |obj| obj.__send__(self) } end
  end
end
 
puts
puts "One call"
n = 100_000
Benchmark.bmbm(15) do |bm|
  bm.report('#map:') { (0..n).map {|i| i.floor } }
  bm.report('Symbol#to_proc:') { (0..n).map(&:floor) }
  bm.report('#every:') { (0..n).every.floor }
end
 
puts
puts "Two calls"
n = 100_000
Benchmark.bmbm(15) do |bm|
  bm.report('#map:') { (0..n).map {|i| i.floor.next } }
  bm.report('#map (x2):') { (0..n).map {|i| i.floor }.map {|i| i.next } }
  bm.report('Symbol#to_proc:') { (0..n).map(&:floor).map(&:next) }
  bm.report('#every:') { (0..n).every.floor.every.next }
  bm.report('#every (chain):') { (0..n).every { floor.next } }
end