Open
Description
.chain can link multiple Enumerables into a single efficient iterator.
# bad
(a + b).map { |x| 42 + x }
# good
a.chain(b).map { |x| 42 + x }
Unlike +
, it doesn't allocate an intermediate result:
require 'memory_profiler'
a = (1..1000).to_a
b = (1..1000).to_a
MemoryProfiler.report { (a + b).map {} }.pretty_print
MemoryProfiler.report { a.chain(b).map {} }.pretty_print
with +
:
allocated memory by class
-----------------------------------
32080 Array
with chain
:
allocated memory by class
-----------------------------------
17784 Array
160 Proc
56 Enumerator::Chain
Metadata
Metadata
Assignees
Labels
No labels