Skip to content

Instantly share code, notes, and snippets.

@protist
Created September 11, 2014 02:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save protist/f6d344cdc59571947677 to your computer and use it in GitHub Desktop.
Save protist/f6d344cdc59571947677 to your computer and use it in GitHub Desktop.
Benchmark to compare accessing sequential items in an array. Firstly, array is accessed via an incrementing index. Secondly, array is accessed after conversion into an enumerator.
#!/usr/bin/env ruby
require 'benchmark'
max = 1_000_000
a = (1..max).to_a
Benchmark.bmbm do |bm|
bm.report('array[index]') do # Over 20 times faster than using enum.next.
i = 0
while i < max
a[i]
i += 1
end
end
bm.report('enum.next') do
e = a.to_enum
i = 0
while i < max
e.next
i += 1
end
end
bm.report('enum.next with rescue') do # In reality, we need to rescue enum.next.
e = a.to_enum
i = 0
while i < max
begin
e.next
rescue StopIteration
nil
end
i += 1
end
end
bm.report('enum.next with times') do # Using times is even slower.
e = a.to_enum
max.times do
e.next
end
end
end
@protist
Copy link
Author

protist commented Sep 11, 2014

                            user     system      total        real
array[index]            0.030000   0.000000   0.030000 (  0.032193)
enum.next               0.550000   0.110000   0.660000 (  0.656447)
enum.next with rescue   0.570000   0.090000   0.660000 (  0.662478)
enum.next with times    0.570000   0.110000   0.680000 (  0.675471)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment