Created
September 3, 2013 19:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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