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

Add new Performance/IoReadlines cop #127

Merged
merged 1 commit into from
Jun 23, 2020
Merged

Conversation

fatkodima
Copy link
Contributor

@fatkodima fatkodima commented Jun 6, 2020

IO (and File as a subclass)readlines class (and instance) methods read full content into memory, which can be inefficient and not necessary. This cop helps to identify such places. Specifically, when readlines method is followed by one of Enumerable methods, we can safely replace it with each_line, which reads one line at a time thus saving memory.

We can autocorrect usages of instance level #readlines method, but cannot for class level .readlines method due to its signature. We can only show an offense and user should manually correct it.

# bad
File.readlines('testfile').each { |l| puts l }
IO.readlines('testfile', chomp: true).each { |l| puts l }

conn.readlines(10).map { |l| l.size }
file.readlines.find { |l| l.start_with?('#') }
file.readlines.each { |l| puts l }

# good
File.open('testfile', 'r').each_line { |l| puts l }
IO.open('testfile').each_line(chomp: true) { |l| puts l }

conn.each_line(10).map { |l| l.size }
file.each_line.find { |l| l.start_with?('#') }
file.each_line { |l| puts l }

@fatkodima
Copy link
Contributor Author

Updated.

config/default.yml Outdated Show resolved Hide resolved
@bbatsov
Copy link
Contributor

bbatsov commented Jun 12, 2020

Btw, are there any references we can link to cops like this one? E.g. from Fast Ruby or something like that? I think that'd be useful to the end users who are going over the docs.

@fatkodima
Copy link
Contributor Author

Updated:

  1. made cop disabled by default
  2. added reference (there are no anything related in fast-ruby repo, but found a good section in gitlab docs).

@fatkodima fatkodima changed the title Add new Performance/Readlines cop Add new Performance/IoReadlines cop Jun 12, 2020
@koic koic merged commit befd184 into rubocop:master Jun 23, 2020
@koic
Copy link
Member

koic commented Jun 23, 2020

Thanks!

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

Successfully merging this pull request may close these issues.

None yet

3 participants