Skip to content

Instantly share code, notes, and snippets.

@libkazz
Created March 11, 2024 02:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save libkazz/c1ef5dcee20b93d3f0898ddfcaa944ae to your computer and use it in GitHub Desktop.
Save libkazz/c1ef5dcee20b93d3f0898ddfcaa944ae to your computer and use it in GitHub Desktop.
# This code is based on the code at blow:
# https://github.com/fastruby/fast-ruby/tree/main/code/enumerable
require "benchmark/ips"
ARRAY = [*1..100]
def fast
ARRAY.each.with_index(1) do |number, index|
index
end
end
def slow
ARRAY.each_with_index do |number, index|
index + 1
end
end
Benchmark.ips do |x|
x.report("each.with_index") { fast }
x.report("each_with_index") { slow }
x.compare!
end
# ruby 3.2.2 (2023-03-30 revision e51014f9c0) [x86_64-darwin22]
# Warming up --------------------------------------
# each.with_index 11.362k i/100ms
# each_with_index 10.486k i/100ms
# Calculating -------------------------------------
# each.with_index 114.349k (± 0.7%) i/s - 579.462k in 5.067760s
# each_with_index 105.667k (± 0.5%) i/s - 534.786k in 5.061186s
#
# Comparison:
# each.with_index: 114348.7 i/s
# each_with_index: 105666.7 i/s - 1.08x slower
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment