Skip to content

Instantly share code, notes, and snippets.

@mikelikesbikes
Created April 18, 2012 05:08
Show Gist options
  • Select an option

  • Save mikelikesbikes/2411214 to your computer and use it in GitHub Desktop.

Select an option

Save mikelikesbikes/2411214 to your computer and use it in GitHub Desktop.
comparing frequency built using different enumerable methods
require 'benchmark'
Enumerable.class_eval do
def frequency_group_by
group_by{|x| x}.map { |x, xs| [x, xs.length] }
end
def frequency_each
h = Hash.new(0)
each { |x| h[x] += 1 }
h.to_a
end
def frequency_reduce
reduce(Hash.new(0)) { |h, x| h[x] += 1; h }.to_a
end
end
def run_benchmark(arr_size)
arr = Array.new(arr_size) { rand(1000) }
n = 1000
unless arr.frequency_each == arr.frequency_reduce && arr.frequency_reduce == arr.frequency_group_by
puts "sanity check... failed."
exit
end
Benchmark.bm do |x|
x.report("freq w/ group_by: ") { n.times { arr.frequency_group_by }}
x.report("freq w/ each: ") { n.times { arr.frequency_each }}
x.report("freq w/ reduce: ") { n.times { arr.frequency_reduce }}
end
end
run_benchmark(10000)
# Output
# user system total real
# freq w/ group_by: 5.060000 0.140000 5.200000 ( 5.210313)
# freq w/ each: 5.170000 0.040000 5.210000 ( 5.218802)
# freq w/ reduce: 10.190000 0.090000 10.280000 ( 10.287221)
@mikelikesbikes

Copy link
Copy Markdown
Author

I'm very surprised by the difference in performance between each and reduce (the code is nearly identical... even using the same Hash structure). Any ideas why the order of magnitude difference?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment