Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Ruby Benchmark: Starting a loop at index 1
# gem install benchmark-ips
require "benchmark/ips"
Benchmark.ips do |x|
x.report("range") { (1..100).each { |i| i } }
x.report("upto") { 1.upto(100).each { |i| i } }
x.report("times plus one") { 100.times { |i| i + 1 } }
x.report("times.with_index") { 100.times.with_index(1) { |_, i| i } }
x.compare!
end
Warming up --------------------------------------
range 14.417k i/100ms
upto 10.648k i/100ms
times plus one 11.611k i/100ms
times.with_index 8.872k i/100ms
Calculating -------------------------------------
range 152.190k (± 9.1%) i/s - 764.101k in 5.073210s
upto 135.615k (± 7.4%) i/s - 681.472k in 5.056277s
times plus one 132.532k (±13.2%) i/s - 661.827k in 5.140156s
times.with_index 91.575k (± 9.3%) i/s - 452.472k in 5.005000s
Comparison:
range: 152189.8 i/s
upto: 135615.3 i/s - same-ish: difference falls within error
times plus one: 132532.2 i/s - same-ish: difference falls within error
times.with_index: 91575.2 i/s - 1.66x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment