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)
@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