Created
July 16, 2009 13:36
-
-
Save Narnach/148408 to your computer and use it in GitHub Desktop.
A fast version of Enumerable#group_by.
This file contains hidden or 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
| # 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