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

Use !empty? or .any? instead of .count > 0 #9234

Merged
merged 6 commits into from Feb 6, 2019
Merged

Conversation

monfresh
Copy link
Contributor

@monfresh monfresh commented Feb 6, 2019

Why: When checking if an array contains elements, !empty (or
size > 0) is faster than count > 0. count should rarely be used in
a Rails application.

When checking if an ActiveRecord::Relation contains results, .any? is
preferred because it runs a SELECT 1 AS one LIMIT 1 SQL query as
opposed to a COUNT, which can be very slow on a large table. In all
of the instances changed in this PR, we don't care about the actual
count of elements, so count is not the right choice.

Recommended reading:
https://www.speedshop.co/2019/01/10/three-activerecord-mistakes.html

**Why**: When checking if an array contains elements, `!empty` (or
`size > 0`) is faster than `count > 0`. `count` should rarely be used in
a Rails application.

When checking if an ActiveRecord::Relation contains results, `.any?` is
preferred because it runs a `SELECT 1 AS one LIMIT 1` SQL query as
opposed to a `COUNT`, which can be very slow on a large table. In all
of the instances changed in this PR, we don't care about the actual
count of elements, so `count` is not the right choice.

Recommended reading:
https://www.speedshop.co/2019/01/10/three-activerecord-mistakes.html
@ghost ghost assigned monfresh Feb 6, 2019
@ghost ghost added the In-Progress label Feb 6, 2019
Copy link
Contributor

@pkarman pkarman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm!

@monfresh monfresh added Ready-to-Merge This PR is ready to be merged and will be picked up by va-bot to automatically merge to master and removed In-Progress labels Feb 6, 2019
@ghost ghost assigned va-bot Feb 6, 2019
@ghost ghost added the In-Progress label Feb 6, 2019
@va-bot va-bot merged commit 5bdd3f8 into master Feb 6, 2019
@va-bot va-bot deleted the mb-replace-count-with-any branch February 6, 2019 19:00
@ghost ghost removed the In-Progress label Feb 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Ready-to-Merge This PR is ready to be merged and will be picked up by va-bot to automatically merge to master
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants