Fix for JRUBY-2882. Handle error messages related to constructors better
[jruby.git] / bench / bench_loops.rb
blob850bcf0f98f72dbff0eddeb7fed91a48ba0d6eb8
1 # Copied with permission from Antoni Cangiano's blog:
2 # http://antoniocangiano.com/2008/03/25/inject-each-and-times-methods-much-slower-in-ruby-19
3 require 'benchmark'
4 include Benchmark
6 class Integer
7   def sum_with_inject
8     (1..self).inject(0) { |sum, i| sum + i }
9   end
11   def sum_with_each
12     sum = 0
13     (1..self).each { |i| sum += i }
14     sum
15   end
17   def sum_with_times
18     sum = 0
19     (self+1).times { |i| sum += i}
20     sum
21   end
23   def sum_with_while
24     sum, i = 0, 1
25     while i <= self
26       sum += i
27       i += 1
28     end
29     sum
30   end
31 end
33 (1..8).each do |p|
34   n = 10**p
35   puts "=== 10^#{p} ==="
36   benchmark do |x|
37     x.report("inject: ") { n.sum_with_inject }
38     x.report("each:   ") { n.sum_with_each }
39     x.report("times:  ") { n.sum_with_times }
40     x.report("while:  ") { n.sum_with_while }
41   end
42 end