Skip to content

Instantly share code, notes, and snippets.

@chills42
Forked from omockler/group_vs_push.rb
Last active August 29, 2015 14:24
Show Gist options
  • Save chills42/21c3bb031db85e3fa508 to your computer and use it in GitHub Desktop.
Save chills42/21c3bb031db85e3fa508 to your computer and use it in GitHub Desktop.
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
def partition
even, odd = (0..99).partition { |i| i % 2 == 0 }
end
Benchmark.ips do |x|
x.report("group") { |times| times.times do group; end }
x.report("push") { |times| times.times do push; end }
x.report("partition") { |times| times.times do partition; end }
x.compare!
end
Calculating -------------------------------------
group 6.271k i/100ms
push 8.137k i/100ms
partition 7.757k i/100ms
-------------------------------------------------
group 67.303k (± 4.7%) i/s - 338.634k
push 90.062k (± 4.4%) i/s - 455.672k
partition 84.044k (± 4.5%) i/s - 426.635k
Comparison:
push: 90061.7 i/s
partition: 84043.5 i/s - 1.07x slower
group: 67303.2 i/s - 1.34x slower
Calculating -------------------------------------
group 6.797k i/100ms
push 8.703k i/100ms
partition 8.164k i/100ms
-------------------------------------------------
group 70.667k (± 3.9%) i/s - 353.444k
push 89.336k (± 4.6%) i/s - 452.556k
partition 83.469k (± 4.7%) i/s - 424.528k
Comparison:
push: 89336.3 i/s
partition: 83468.8 i/s - 1.07x slower
group: 70667.3 i/s - 1.26x slower
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment