Skip to content

Instantly share code, notes, and snippets.

@spajus
Last active August 29, 2015 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spajus/7b29735a1777d9fa153a to your computer and use it in GitHub Desktop.
Save spajus/7b29735a1777d9fa153a to your computer and use it in GitHub Desktop.
Ruby benchmark: call a method on every object in array.
require 'benchmark'
class Something
def initialize(stuff)
@stuff = stuff
end
def update
@stuff += 0.1
end
end
array = []
10_000_000.times { array << Something.new(rand) }
Benchmark.bm(10) do |b|
b.report('for:') { for x in array; x.update end; }
b.report('for len:') { for x in 0..array.size-1; array[x].update end; }
b.report('each:') { array.each { |x| x.update } }
b.report('each(:&):') { array.each(&:update) }
b.report('map:') { array.map { |x| x.update } }
b.report('map(:&):') { array.map(&:update) }
end

1.9.3

                 user     system      total        real
for:         2.650000   0.130000   2.780000 (  2.793241)
for len:     2.440000   0.070000   2.510000 (  2.496054)
each:        1.400000   0.000000   1.400000 (  1.400599)
each(:&):    0.980000   0.000000   0.980000 (  0.983123)
map:         1.710000   0.030000   1.740000 (  1.744674)
map(:&):     1.460000   0.030000   1.490000 (  1.485941)

2.0.0

                 user     system      total        real
for:         1.160000   0.020000   1.180000 (  1.173280)
for len:     1.260000   0.000000   1.260000 (  1.262339)
each:        1.130000   0.000000   1.130000 (  1.125609)
each(:&):    1.130000   0.000000   1.130000 (  1.135357)
map:         1.300000   0.030000   1.330000 (  1.325807)
map(:&):     1.310000   0.020000   1.330000 (  1.328399)

2.1.1

                 user     system      total        real
for:         1.120000   0.020000   1.140000 (  1.134307)
for len:     1.170000   0.000000   1.170000 (  1.176002)
each:        1.070000   0.000000   1.070000 (  1.071600)
each(:&):    1.070000   0.000000   1.070000 (  1.062117)
map:         1.250000   0.030000   1.280000 (  1.281382)
map(:&):     1.240000   0.030000   1.270000 (  1.268126)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment