Manoj M J
Manoj M J

Reputation: 449

Rails Activerecord: Map vs pluck vs as_json

My question is purely based on the performance impact of the 3 approaches. I need to know which is the best method to use for the task at hand.

I need to render json for a specific set of records.

The current approach I use is

result = User.all.map{ |u| { name: u.name, id: u.id } }

As you may know, this will loop through Activerecord objects and this will have very low performance for a large set of records.

Alternative approach is to use pluck.

result = User.all.pluck(:name,:id).map{ |u| { name: u[0], id: u[1] } }

Probably much better in performance, but code looks smelly.

The same can be achieved with as_json if we override as_json as include only the necessary parameters but I need to know if this will also iterate through activerecord objects.

Feel free to say if there is any other approach which will give better performance.

Upvotes: 2

Views: 2086

Answers (2)

kwerle
kwerle

Reputation: 2401

result = User.all.as_json(only: [:name, :id])

Upvotes: 0

spickermann
spickermann

Reputation: 106882

You could just use:

User.select(:id, :name).to_json

It might not be as performant as your pluck(...).map version which is indeed very low level. But it is faster than your all.map version and more elegant (aka easier to read).

Upvotes: 2

Related Questions