diff options
author | Akira Matsuda <ronnie@dio.jp> | 2013-07-10 22:29:11 +0900 |
---|---|---|
committer | Akira Matsuda <ronnie@dio.jp> | 2013-07-10 22:59:32 +0900 |
commit | f660abce9a39a23dfa7494ca856f2ae9e824f806 (patch) | |
tree | b4120e20d892e21214bd65f13b14662c7e5e53f3 /activesupport/lib | |
parent | 453617006a5481fda9b3e7639d9049a2a281a2da (diff) | |
download | rails-f660abce9a39a23dfa7494ca856f2ae9e824f806.tar.gz rails-f660abce9a39a23dfa7494ca856f2ae9e824f806.tar.bz2 rails-f660abce9a39a23dfa7494ca856f2ae9e824f806.zip |
Speed up Array#split
Benchmark:
user system total real
old 0.510000 0.000000 0.510000 ( 0.506749)
new 0.330000 0.000000 0.330000 ( 0.336187)
Diffstat (limited to 'activesupport/lib')
-rw-r--r-- | activesupport/lib/active_support/core_ext/array/grouping.rb | 26 |
1 files changed, 20 insertions, 6 deletions
diff --git a/activesupport/lib/active_support/core_ext/array/grouping.rb b/activesupport/lib/active_support/core_ext/array/grouping.rb index dbddc7a7b4..36896f9614 100644 --- a/activesupport/lib/active_support/core_ext/array/grouping.rb +++ b/activesupport/lib/active_support/core_ext/array/grouping.rb @@ -86,13 +86,27 @@ class Array # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]] # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]] def split(value = nil, &block) - inject([[]]) do |results, element| - if block && block.call(element) || value == element - results << [] - else - results.last << element - end + if block + inject([[]]) do |results, element| + if block.call(element) + results << [] + else + results.last << element + end + results + end + else + results, arr = [[]], self + until arr.empty? + if (idx = index(value)) + results.last.concat(arr.shift(idx)) + arr.shift + results << [] + else + results.last.concat(arr.shift(arr.size)) + end + end results end end |