Skip to content

Cop idea: prefer a.chain(b) over a + b when iterating #461

Open
@vlad-pisanov

Description

@vlad-pisanov

.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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions