Skip to content

Instantly share code, notes, and snippets.

@carlosantoniodasilva
Created September 3, 2013 19:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save carlosantoniodasilva/6428702 to your computer and use it in GitHub Desktop.
Save carlosantoniodasilva/6428702 to your computer and use it in GitHub Desktop.
Benchmark while vs each_with_index. RE: https://github.com/rails/rails/pull/12065
require 'benchmark/ips'
ARRAY = [1,2,3,1,'2',4,'5',6,7,8,9,'10']
Benchmark.ips do |x|
x.report("while") {
hash = {}
index = 0
length = ARRAY.length
while index < length
hash[index] = ARRAY[index]
index += 1
end
hash
}
x.report("each_with_index") {
hash = {}
ARRAY.each_with_index do |item, index|
hash[index] = item
end
hash
}
end
=begin
Calculating -------------------------------------
while 25622 i/100ms
each_with_index 18032 i/100ms
-------------------------------------------------
while 333404.8 (±16.7%) i/s - 1178612 in 5.521999s
each_with_index 208629.7 (±15.4%) i/s - 1009792 in 5.001059s
real 0m16.952s
user 0m15.690s
sys 0m1.194s
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment