Created
June 21, 2025 16:58
-
-
Save alexanderadam/37b1c5696232389f51229274ca3d49bd to your computer and use it in GitHub Desktop.
each_with_index vs each.with_index
This file contains hidden or 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
#!/usr/bin/env ruby | |
require "benchmark/ips" | |
# ruby 3.3.6 (2024-11-05 revision 75015d4c1f) [x86_64-linux] | |
# Warming up -------------------------------------- | |
# each.with_index 2.460k i/100ms | |
# each_with_index 3.613k i/100ms | |
# Calculating ------------------------------------- | |
# each.with_index 26.436k (± 3.7%) i/s (37.83 μs/i) - 132.840k in 5.032459s | |
# each_with_index 37.158k (± 5.1%) i/s (26.91 μs/i) - 187.876k in 5.070741s | |
# Comparison: | |
# each_with_index: 37158.1 i/s | |
# each.with_index: 26436.1 i/s - 1.41x slower | |
ARRAY = [*1..100] | |
def each_with_index_se | |
ARRAY.each.with_index do |number, index| | |
number + index | |
end | |
end | |
def each_with_index_si | |
ARRAY.each_with_index do |number, index| | |
number + index | |
end | |
end | |
Benchmark.ips do |x| | |
x.report("each.with_index") { each_with_index_se } | |
x.report("each_with_index") { each_with_index_si } | |
x.compare! | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment