Created
September 11, 2014 02:32
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Author
protist
commented
Sep 11, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment