Skip to content

Instantly share code, notes, and snippets.

@mikesea
Last active December 25, 2015 02:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikesea/6905502 to your computer and use it in GitHub Desktop.
Save mikesea/6905502 to your computer and use it in GitHub Desktop.
Comparing for Array#each against for x in Array
require 'benchmark'
array = (1..1000000).map { rand }
Benchmark.bmbm do |x|
x.report("for:") { for num in array; next; end }
x.report("each:") { array.each { |x| next } }
end
# Output, 2 different runs on 1.9.3:
➜ code ruby iterators.rb
Rehearsal -----------------------------------------
for: 0.150000 0.000000 0.150000 ( 0.154021)
each: 0.140000 0.000000 0.140000 ( 0.142896)
-------------------------------- total: 0.290000sec
user system total real
for: 0.160000 0.000000 0.160000 ( 0.160215)
each: 0.140000 0.000000 0.140000 ( 0.147743)
➜ code ruby iterators.rb
Rehearsal -----------------------------------------
for: 0.160000 0.000000 0.160000 ( 0.160084)
each: 0.150000 0.000000 0.150000 ( 0.147410)
-------------------------------- total: 0.310000sec
user system total real
for: 0.160000 0.000000 0.160000 ( 0.164363)
each: 0.150000 0.000000 0.150000 ( 0.147960)
# and on 2.0.0
➜ code ruby iterators.rb
Rehearsal -----------------------------------------
for: 0.050000 0.000000 0.050000 ( 0.048878)
each: 0.040000 0.000000 0.040000 ( 0.045567)
-------------------------------- total: 0.090000sec
user system total real
for: 0.040000 0.000000 0.040000 ( 0.047812)
each: 0.050000 0.000000 0.050000 ( 0.045822)
➜ code ruby iterators.rb
Rehearsal -----------------------------------------
for: 0.050000 0.000000 0.050000 ( 0.048716)
each: 0.050000 0.000000 0.050000 ( 0.046151)
-------------------------------- total: 0.100000sec
user system total real
for: 0.050000 0.000000 0.050000 ( 0.048347)
each: 0.040000 0.000000 0.040000 ( 0.045965)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment