Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created November 9, 2009 13:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jodosha/229951 to your computer and use it in GitHub Desktop.
Save jodosha/229951 to your computer and use it in GitHub Desktop.
Ruby benchmark: Array#each vs for x in array
#!/usr/bin/env ruby -w
require "benchmark"
TIMES = 100_000
ARRAY = (1..1_000).to_a
Benchmark.bm(30) do |b|
b.report "each" do
TIMES.times do |i|
ARRAY.each do |element|
end
end
end
b.report "for ... in" do
TIMES.times do |i|
for x in ARRAY
end
end
end
end
__END__
user system total real
each 9.710000 0.010000 9.720000 ( 9.740620)
for ... in 7.460000 0.000000 7.460000 ( 7.475158)
@os6sense
Copy link

ruby 3.2.1 (2023-02-08 revision 31819e82c8) [x86_64-linux]

                                     user     system      total        real
each                             2.052966   0.000207   2.053173 (  2.053209)
for ... in                       2.225467   0.000006   2.225473 (  2.225489)
for ... in 0..limit              2.478339   0.000000   2.478339 (  2.478365)
while i <ARRAY.size              1.727570   0.000000   1.727570 (  1.727601)
while i <limit                   1.469423   0.000001   1.469424 (  1.469439)

@realhaidinh
Copy link

ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x64-mingw-ucrt]

                                   user     system      total        real
each                             4.203000   0.000000   4.203000 (  4.222868)
for ... in                       4.562000   0.000000   4.562000 (  4.583148)
for ... in 0..limit              5.047000   0.000000   5.047000 (  5.050032)
while i <ARRAY.size              2.219000   0.000000   2.219000 (  2.235048)
while i <limit                   1.984000   0.000000   1.984000 (  2.017428)

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