From 04460303152b6c09e0b6ce6d30cb9958caac4b74 Mon Sep 17 00:00:00 2001 From: Nick LaMuro Date: Thu, 9 Aug 2018 19:07:14 -0500 Subject: [PATCH 1/2] Use .count, not .length, for better performance `.length` on an `ActiveRecord::Relation` object will trigger `ActiveRecord::Base#load`, which will execute the current query, and then do a count on that array-like object. `.count` will make use of the database adapter's SQL `COUNT` call, and wrap the current `SELECT` statement in a `COUNT(...)`, which will only return the integer value for the number records that would have been returned if that query was otherwise run without the `COUNT`. Since in this case, we are simply using this as an aggregation for a summary view, the `.count` method is vastly prefered over the `.length` as doing `.length` will instantiate all the `ActiveRecord` objects in memory for all of the records before counting the records in ruby. Doing the same with `.count` not only is faster in ruby, but it is less strain on the DB as well, since it won't have to transmit almost any data over the wire as well. --- app/services/ems_dashboard_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/ems_dashboard_service.rb b/app/services/ems_dashboard_service.rb index 3241131695e..c3f769fc113 100644 --- a/app/services/ems_dashboard_service.rb +++ b/app/services/ems_dashboard_service.rb @@ -51,7 +51,7 @@ def format_data(ems_type, attributes, attr_icon, attr_url, attr_hsh) :id => attr_hsh[attr] + '_' + @ems_id, :iconClass => attr_icon[attr], :title => attr_hsh[attr], - :count => @ems.send(attr).length, + :count => @ems.send(attr).count, :href => get_url(ems_type, @ems_id, attr_url[attr]), :notification => { :iconClass => 'pficon pficon-error-circle-o', From 0cff4de6dcc81a5daa1329717b26178064ba3843 Mon Sep 17 00:00:00 2001 From: Nick LaMuro Date: Thu, 9 Aug 2018 19:12:54 -0500 Subject: [PATCH 2/2] Use a more idiomatic way of building strings String interpolation is the much preferred way to join strings in Ruby, and also avoids issues were `:+` can sometimes not work as expected. Worth noting: I was getting errors on this line when running the code locally when `@ems_id` was an integer. It might be that in the controller, it is passed in as a string, but this way, either works and Ruby will convert it as needed. --- app/services/ems_dashboard_service.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/services/ems_dashboard_service.rb b/app/services/ems_dashboard_service.rb index c3f769fc113..919601c856b 100644 --- a/app/services/ems_dashboard_service.rb +++ b/app/services/ems_dashboard_service.rb @@ -48,7 +48,7 @@ def format_data(ems_type, attributes, attr_icon, attr_url, attr_hsh) attr_data = [] attributes.each do |attr| attr_data.push( - :id => attr_hsh[attr] + '_' + @ems_id, + :id => "#{attr_hsh[attr]}_#{@ems_id}", :iconClass => attr_icon[attr], :title => attr_hsh[attr], :count => @ems.send(attr).count,