Skip to content

Instantly share code, notes, and snippets.

@zaratan
Forked from carlosantoniodasilva/while-vs-each_with_index.rb
Last active March 8, 2021 05:47
Show Gist options
  • Save zaratan/4767b7829d3e5cea0ff0735fcc86d9e8 to your computer and use it in GitHub Desktop.
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
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
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
@zaratan
Copy link
Author

zaratan commented Mar 8, 2021

Ruby 2.7.2, mbp 16" 2019

Warming up --------------------------------------
                 for    66.319k i/100ms
                 map    74.178k i/100ms
Calculating -------------------------------------
                 for    679.577k (± 2.4%) i/s -      3.449M in   5.077525s
                 map    750.524k (± 2.5%) i/s -      3.783M in   5.043778s
Warming up --------------------------------------
               while    64.774k i/100ms
     each_with_index    52.388k i/100ms
Calculating -------------------------------------
               while    756.853k (±12.2%) i/s -      3.757M in   5.041195s
     each_with_index    532.295k (± 8.2%) i/s -      2.672M in   5.055235s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment