Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
vlad-pisanov opened this issue Aug 30, 2024 · 0 comments
Open

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

vlad-pisanov opened this issue Aug 30, 2024 · 0 comments

Comments

@vlad-pisanov
Copy link
Contributor

.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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant