Skip to content

Instantly share code, notes, and snippets.

@kenchan
Last active April 13, 2021 06:28
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 kenchan/c73a3c98a6a39bc21cfd6c213dfd1caf to your computer and use it in GitHub Desktop.
Save kenchan/c73a3c98a6a39bc21cfd6c213dfd1caf to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
Benchmark.ips do |x|
x.report("each") do
s = 0
(10 ** 5).times.each do |i|
s += i
end
end
x.report("inject") do
(10 ** 5).times.inject(0) do |acc, i|
acc + i
end
end
x.compare!
end
[15:23:20] ~ via 💎 v3.0.1
❯ ruby each_vs_inject.rb
Warming up --------------------------------------
each 24.000 i/100ms
inject 16.000 i/100ms
Calculating -------------------------------------
each 227.144 (± 3.5%) i/s - 1.152k in 5.078252s
inject 137.510 (± 9.5%) i/s - 688.000 in 5.052515s
Comparison:
each: 227.1 i/s
inject: 137.5 i/s - 1.65x (± 0.00) slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment