Skip to content

Instantly share code, notes, and snippets.

@guizmaii
Forked from jodosha/each_benchmark.rb
Created December 10, 2018 19:59
Show Gist options
  • Save guizmaii/52fa1d1ce186488256984f95aa464e77 to your computer and use it in GitHub Desktop.
Save guizmaii/52fa1d1ce186488256984f95aa464e77 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment