rubocop-performance
rubocop-performance copied to clipboard
[Request]: A cop that detects unnecessary duplication of objects
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.
Performance/ChainArrayAllocation
already handles this for arrays:
https://docs.rubocop.org/rubocop-performance/cops_performance.html#performancechainarrayallocation
Awesome! Thanks for the info @eugeneius Keeping this open to extend handling to String duplication.