Skip to content

New cop: Performance/ChainedHashMerge #526

Description

@sucicfilip

Is your feature request related to a problem? Please describe.

Chained .merge calls create unnecessary intermediate hash objects.

Since Ruby 2.6, Hash#merge accepts multiple arguments. However, chained calls such as:

hash.merge(a).merge(b)
hash.merge(a).merge(b).merge(c)

allocate a new Hash object for each call in the chain.

This results in avoidable object allocations and additional GC pressure.

Microbenchmark (Ruby 3.4.7, arm64-darwin23, 1_000_000 iterations):

chained: 0.3225s
multi:   0.1525s

Using the multi-argument form is ~2x faster in this simple benchmark.

Benchmark snippet:

require 'benchmark'

a = {a: 1}
b = {b: 2}
c = {c: 3}
base = {}

Benchmark.bm do |x|
  x.report("chained") { 1_000_000.times { base.merge(a).merge(b).merge(c) } }
  x.report("multi")   { 1_000_000.times { base.merge(a, b, c) } }
end

Describe the solution you'd like

Introduce a new cop: Performance/ChainedHashMerge.

The cop would detect chained merge, merge!, and update calls and suggest collapsing them into a single multi-argument call when safe.

Examples:

# bad
hash.merge(a).merge(b)
hash.merge(a).merge(b).merge(c)

# good
hash.merge(a, b)
hash.merge(a, b, c)

And for destructive variants:

# bad
hash.merge!(a).merge!(b)

# good
hash.merge!(a, b)

The cop should:

  • Require Ruby >= 2.6
  • Skip autocorrection when a block is provided (since hash.merge(a).merge(b) { ... } is not equivalent to hash.merge(a, b) { ... })
  • Likely be marked as unsafe, since the receiver type cannot always be statically determined

Describe alternatives you've considered

One alternative is to rely on manual code review or developer awareness of multi-argument merge.

However, this pattern is easy to overlook, and the performance difference can be significant in hot paths. Automating detection via a cop would make the optimization consistent and discoverable.

Additional context

This would be my first contribution to the repository. I’d be happy to implement the cop if maintainers agree that it fits within rubocop-performance.

...

Running grep across real-world-ruby-apps (https://github.com/jeromedalbert/real-world-ruby-apps):
jekyll, vagrant, chef, homebrew, rubocop, puppet, geocoder, whenever...
20 occurrences across well-known projects

According to this GH search, it isn't a rare pattern, with more than 14k results.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions