Skip to content

Instantly share code, notes, and snippets.

@jodosha
Created November 9, 2009 13:49
Show Gist options
  • 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)
@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)

@mkweick
Copy link

mkweick commented Jun 2, 2024

ruby 3.3.1 (2024-04-23 revision c56cd86388) [x86_64-linux]

                                     user     system      total        real
each                             3.574591   0.000000   3.574591 (  3.586114)
for ... in                       3.879859   0.000000   3.879859 (  3.892989)
for ... in 0..limit              4.631031   0.000000   4.631031 (  4.637611)
while i <ARRAY.size              2.519849   0.000000   2.519849 (  2.520258)
while i <limit                   1.927129   0.000000   1.927129 (  1.927600)

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