Which performance is better, ActiveRecord or Array, when performing multiple records narrowing in rails?

Asked 1 years ago, Updated 1 years ago, 76 views

This is a performance discussion regarding how to narrow down records in the development of rails applications.

When performing multiple record narrowing, which is better in response memory, using SQL conditions in ActiveRecord or filtering with ruby's array manipulation method?
For example, if I want to get the number of cases per type from the User model as shown below, which pattern is considered good from a performance perspective?

#pattern 1:issue SQL for each type to retrieve
@user_type1_count = User.where(type:1).count
@user_type2_count = User.where(type:2).count
@user_type3_count = User.where(type:3).count

# Pattern 2: Retrieve all of the target records and then narrow them down to an array (SQL is issued only once)
@users=User.all
@[email protected] { | user|user.type==1}
@[email protected] { | user|user.type==2}
@[email protected] { | user|user.type==3}

In my opinion, I thought pattern 2 with a small number of SQL issues might be better, but it's just a sensory prediction, so I'd like to take your advice.
Of course, it depends on the number of records in the entire User table and the processing content before and after.I would appreciate it if you could give me an answer with that in mind.

ruby-on-rails ruby rails-activerecord

2022-09-30 21:47

1 Answers

It depends on the number of cases and the contents of the data, but in most cases, it is faster to leave it to DB.
Also, if you use group by and distinct, you can get a single SQL number.

User.select(:type).distinct.group(:type).count


2022-09-30 21:47

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.