File: index_v_take_while.rb

package info (click to toggle)
ruby-rspec 3.12.0c0e1m1s0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 6,752 kB
  • sloc: ruby: 69,818; sh: 1,861; makefile: 99
file content (47 lines) | stat: -rw-r--r-- 854 bytes parent folder | download | duplicates (6)
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
require 'benchmark'

n = 10000

list = 1.upto(10).to_a

Benchmark.benchmark do |bm|
  puts "take_while"
  3.times do
    bm.report do
      n.times do
        list.
          take_while {|i| i < 6}.
          map {|i| i}.
          compact
      end
    end
  end

  puts

  puts "list[0,n]"
  3.times do
    bm.report do
      n.times do
        if index = list.index(6)
          list[0, index].map {|i| i.to_s}
        else
          list.map {|i| i}.compact
        end
      end
    end
  end
end

__END__

ruby benchmarks/index_v_take_while.rb
take_while
   0.020000   0.000000   0.020000 (  0.020005)
   0.010000   0.000000   0.010000 (  0.015907)
   0.010000   0.000000   0.010000 (  0.015962)

list[0,n]
   0.020000   0.000000   0.020000 (  0.023561)
   0.020000   0.000000   0.020000 (  0.018812)
   0.030000   0.000000   0.030000 (  0.022389)