Skip to content

Commit f660abc

Browse files
committed
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)
1 parent 4536170 commit f660abc

File tree

1 file changed

+20
-6
lines changed
  • activesupport/lib/active_support/core_ext/array

1 file changed

+20
-6
lines changed

activesupport/lib/active_support/core_ext/array/grouping.rb

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,27 @@ def in_groups(number, fill_with = nil)
8686
# [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
8787
# (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
8888
def split(value = nil, &block)
89-
inject([[]]) do |results, element|
90-
if block && block.call(element) || value == element
91-
results << []
92-
else
93-
results.last << element
94-
end
89+
if block
90+
inject([[]]) do |results, element|
91+
if block.call(element)
92+
results << []
93+
else
94+
results.last << element
95+
end
9596

97+
results
98+
end
99+
else
100+
results, arr = [[]], self
101+
until arr.empty?
102+
if (idx = index(value))
103+
results.last.concat(arr.shift(idx))
104+
arr.shift
105+
results << []
106+
else
107+
results.last.concat(arr.shift(arr.size))
108+
end
109+
end
96110
results
97111
end
98112
end

0 commit comments

Comments
 (0)