Super small queries optimizations #1586
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
What type of PR is this? (check all applicable)
Description
I applied two micro optimizations, more in the spirit of following good practices than actual overall performance improvements.
replaced
find_by().nil?withexists?because in those situations the object loaded by find_by is never used, thus is more efficient in general to just ask the DB for what you actually want (in this case to reply to the question asked by thenil?predicate)replaced
any?withpresent?to populate the list of users of an organization. The reasoning is the following: most organizations will most likely exist with users than without, so we usepresent?which preloads the list of users used by the subsequent iteration. Hence 1 query instead of 2.Related Tickets & Documents
This is most definitely the result of me digging through the code after reading 3 ActiveRecord Mistakes That Slow Down Rails Apps: Count, Where and Present.
I'm well aware that these two optimizations don't amount to much at the end of the day, it's more an attempt to hopefully cement good practices when they make sense.
At a first glance I didn't find anything else (though I didn't feel comfortable enough to delve in possible
where()optimizations TBH, especially without hard numbers in front of me), so kudos to everyone!Well, I already knew dev.to was fast 馃敟
Added to documentation?