Skip to content

Instantly share code, notes, and snippets.

@Narnach
Created July 16, 2009 13:36
Show Gist options
  • Select an option

  • Save Narnach/148408 to your computer and use it in GitHub Desktop.

Select an option

Save Narnach/148408 to your computer and use it in GitHub Desktop.
A fast version of Enumerable#group_by.
# Basis for fast_group_by gem: http://github.com/Narnach/fast_group_by
module Enumerable
# An unordered group_by implementation that is a gazillion times faster than
# ActiveSupport's ordered version, when used with large data sets.
# ActiveSupport uses OrderedHash, which are nested Arrays. Array#assoc is
# way slower than Hash#[] because it does a linear search vs a tree search.
# For small data sets, the difference is not that obvious, but in the range
# of 50k+ items, the difference can be 60 seconds vs less than 1 second.
def fast_group_by(&block)
res = Hash.new { |hash, key| hash[key] = [] }
each do |e|
res[block.call(e)] << e
end
res
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment