Patch #24839

Minor performance improvement - Replace count by exists?

Added by Vincent Robert 2 months ago. Updated 2 months ago.

Status:ClosedStart date:
Priority:NormalDue date:
Assignee:Jean-Philippe Lang% Done:

0%

Category:Performance
Target version:3.4.0

Description

When checking to see if a query returns any records, we should use the ActiveRecord exists? method instead of count.

Here is an example in the versions/show.html.erb file:

diff --git a/app/views/versions/show.html.erb b/app/views/versions/show.html.erb
index 82bd572..fc22a9f 100644
--- a/app/views/versions/show.html.erb
+++ b/app/views/versions/show.html.erb
@@ -32,7 +32,7 @@
 <% end %>

 <div id="status_by">
-<%= render_issue_status_by(@version, params[:status_by]) if @version.fixed_issues.count > 0 %>
+<%= render_issue_status_by(@version, params[:status_by]) if @version.fixed_issues.exists? %>
 </div>
 </div>

If we compare the generated queries with PostgreSQL: 

SELECT  1 AS one FROM "issues" WHERE "issues"."fixed_version_id" = ??? LIMIT 1;
should be faster than
SELECT COUNT(*) FROM "issues" WHERE "issues"."fixed_version_id" = ???;

use-exists-instead-of-count.diff Magnifier (1.54 KB) Go MAEDA, 2017-01-16 15:57

Associated revisions

Revision 16210
Added by Jean-Philippe Lang 2 months ago

Use exists? instead of count (#24839).

Revision 16211
Added by Jean-Philippe Lang 2 months ago

Use exists? instead of count (#24839).

Patch by Vincent Robert and Go MAEDA.

History

#1 Updated by Go MAEDA 2 months ago

  • File use-exists-instead-of-count.diff added

Thank you for the patch.

I found three more count which can be replaced with exists?. This is an updated patch: use-exists-instead-of-count.diff

Although .count > 0 can be found in app/views/imports/show.html.erb too, I have not changed because of cache efficiency (exactly the same query will be performed just after them).

#2 Updated by Go MAEDA 2 months ago

  • File deleted (use-exists-instead-of-count.diff)

#3 Updated by Go MAEDA 2 months ago

Excluded app/models/project.rb from the patch because of cache efficiency.

#4 Updated by Jean-Philippe Lang 2 months ago

  • Status changed from New to Closed
  • Assignee set to Jean-Philippe Lang
  • Target version set to 3.4.0

Committed, thanks.

Also available in: Atom PDF