Forked from carlosantoniodasilva/while-vs-each_with_index.rb
Last active
March 8, 2021 05:47
-
-
Save zaratan/4767b7829d3e5cea0ff0735fcc86d9e8 to your computer and use it in GitHub Desktop.
Benchmark while vs each_with_index. And for vs map. 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("for") { | |
result = [] | |
for number in ARRAY | |
result << number.to_s | |
end | |
result | |
} | |
x.report("map") { | |
ARRAY.map do |number| | |
number.to_s | |
end | |
} | |
end |
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ruby 2.7.2, mbp 16" 2019