Last active
August 29, 2015 14:24
-
-
Save omockler/75b35f826afb4f55195b to your computer and use it in GitHub Desktop.
Array push vs. Group By
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' | |
def group | |
(0..99).group_by { |i| i % 2 } | |
end | |
def push | |
even = [] | |
odd = [] | |
(0..99).each do |i| | |
if i % 2 == 0 | |
even << i | |
else | |
odd << i | |
end | |
end | |
end | |
Benchmark.ips do |x| | |
x.report("group") { |times| times.times do group; end } | |
x.report("push") { |times| times.times do push; end } | |
x.compare! | |
end | |
group_time = Benchmark.realtime { 100.times do group; end } | |
push_time = Benchmark.realtime { 100.times do push; end } | |
puts "Group: #{group_time * 1000} milliseconds" | |
puts "Proup: #{push_time * 1000} milliseconds" | |
puts "#{(group_time - push_time) * 1000} milliseconds slower" |
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
Calculating ------------------------------------- | |
group 4.960k i/100ms | |
push 6.225k i/100ms | |
------------------------------------------------- | |
group 61.791k (±16.1%) i/s - 297.600k | |
push 79.216k (±10.9%) i/s - 392.175k | |
Comparison: | |
push: 79216.0 i/s | |
group: 61791.3 i/s - 1.28x slower |
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
Calculating ------------------------------------- | |
group 4.801k i/100ms | |
push 5.942k i/100ms | |
------------------------------------------------- | |
group 61.152k (±12.6%) i/s - 302.463k | |
push 77.945k (± 9.2%) i/s - 386.230k | |
Comparison: | |
push: 77944.7 i/s | |
group: 61151.7 i/s - 1.27x slower |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment