rubocop / rubocop-performance

An extension of RuboCop focused on code performance checks.
https://docs.rubocop.org/rubocop-performance
MIT License
681 stars 80 forks source link

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

Open ashmaroli opened 4 years ago

ashmaroli commented 4 years ago

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.

eugeneius commented 4 years ago

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

ashmaroli commented 4 years ago

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