Last active
April 13, 2021 06:28
-
-
Save kenchan/c73a3c98a6a39bc21cfd6c213dfd1caf to your computer and use it in GitHub Desktop.
This file contains 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
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 |
This file contains 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
[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