OK, calm down. I’m not here to promote the use of the getRowCount method over GlideAggregate., but there has been a long running misunderstanding here. getRowCount is not the evil method it’s been made out to be, but using it incorrectly can certainly lead to performance degradation of an instance, especially where larger result sets are involved.
Let me explain this by way of an analogy.
You’re asked by a friend to go to the local shop to pick up some beers for a small gathering. You do as instructed and then arrive at the gathering only to be asked by another friend that they’d like you to take their car to go back to the shop to find out the price of the beers you just purchased.
Now you’ve got a decision to make:
- A) Go back to the shop.
- B) Pull the receipt out of your pocket.
Both will get you the intended result, but one is certainly not as efficient at the other. This is exactly the same for getRowCount (the receipt) and GlideAggregate (going back to the shop). And this is my point, if you are already using GlideRecord to do something with the records, don’t waste platform resources by performing a second query to the database to get a count of the records. Yes, GlideAggregate is always more efficient than getRowCount at getting a count of the rows matching a query condition, but it’s only adding overhead if used in conjunction with GlideRecord for the same query.
Don’t believe me? Well here’s the proof using a simple background script. You can run this in your own instance if you wish.
var timer = new OCTimer();
timer.start("Just GlideRecord");
timer.start("GlideRecord & GlideAggregate");
var grCmdbCi = new GlideRecord('cmdb_ci');
grCmdbCi.query();
gs.info(grCmdbCi.getRowCount())
timer.stop("Just GlideRecord");
timer.start("Just GlideAggregate");
var gaCmdbCi = new GlideAggregate('cmdb_ci');
gaCmdbCi.addAggregate('COUNT');
gaCmdbCi.query();
if(gaCmdbCi.next()) {
gs.info(gaCmdbCi.getAggregate('COUNT'));
}
timer.stop("Just GlideAggregate");
timer.stop("GlideRecord & GlideAggregate");
gs.info(timer.result())
/* OUTPUT
*** Script: 155248
*** Script: 155248
*** Script: DEFAULT Performance Timings
00.425 Just GlideRecord invoked: 1
00.479 GlideRecord & GlideAggregate invoked: 1
00.054 Just GlideAggregate invoked: 1
00.958 [TOTAL] for: DEFAULT Performance Timings
*/
As we can see from the output above, these are the results
Action | Time taken |
Using Just GlideRecord | 0.425 seconds |
Using Just GlideAggregate | 0.054 seconds |
Using both GlideRecord & GlideAggregate | 0.479 seconds |
This shows us exactly what we would expect. GlideAggregate is far superior in terms of speed when it comes to counting records, but if you use it on top of an already required GlideRecord query, you’re simply adding overhead to your script that’s not needed.
ServiceNow did actually update their guidance on this topic in the Tokyo release, though it’s probably gone largely under the radar for those not referring to the GlideRecord API documentation regularly.