Skip to content

Instantly share code, notes, and snippets.

@makaroni4
Created May 14, 2013 13:44
Show Gist options
  • Save makaroni4/5575964 to your computer and use it in GitHub Desktop.
Save makaroni4/5575964 to your computer and use it in GitHub Desktop.
require 'benchmark'
require 'benchmark/ips'
Benchmark.ips do |r|
r.report("group_by") do
(0..1000).group_by { |w| w % 2 == 0 }.values
end
EVEN = 0
ODD = 1
r.report("dumb") do
(0..1000).inject(Array.new(2) { [] }) do |numbers, number|
numbers[number % 2 == 0 ? EVEN : ODD] << number
numbers
end
end
r.report("partition") do
(0..1000).partition(&:even?)
end
end
# Calculating -------------------------------------
# group_by 621 i/100ms
# dumb 529 i/100ms
# partition 915 i/100ms
# -------------------------------------------------
# group_by 6375.8 (±2.1%) i/s - 32292 in 5.067062s
# dumb 5791.0 (±11.0%) i/s - 28566 in 5.003636s
# partition 9492.3 (±11.4%) i/s - 47580 in 5.094445s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment