rubocop-performance icon indicating copy to clipboard operation
rubocop-performance copied to clipboard

[Request]: A cop that detects unnecessary duplication of objects

Open ashmaroli opened this issue 4 years ago • 2 comments

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

Given that strings are an essential data type in a program, apps occasionally initialize a lot of String objects by chaining non-mutating methods.

For example:

def sanitize_input(string)
  string.strip.gsub(pattern, some_string).squeeze(character)
end

Will duplicate the string argument 3 times before returning the result.

Describe the solution you'd like

  string.strip.gsub(pattern, some_string).squeeze(character)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Chaining non-mutating String methods result in unnecessary allocations. Consider refactoring to duplicate `string` once
and mutate that duplicated object thereafter.

While the issue is applicable to more core classes, handling Strings first would be a good start.

ashmaroli avatar Sep 18 '20 14:09 ashmaroli

Performance/ChainArrayAllocation already handles this for arrays: https://docs.rubocop.org/rubocop-performance/cops_performance.html#performancechainarrayallocation

eugeneius avatar Sep 19 '20 12:09 eugeneius

Awesome! Thanks for the info @eugeneius Keeping this open to extend handling to String duplication.

ashmaroli avatar Sep 19 '20 13:09 ashmaroli