NudeCanalTroll
NudeCanalTroll

Reputation: 2286

Rendering large amounts of ActiveRecord objects in Rails

I've got a few Rails controller actions that respond to AJAX requests in this fashion:

books = Book.all
render :json => { :books => books }

This should be relatively quick, however it's taking upwards of 5 seconds, which is far too long for any request on the web. The logs look like this:

Completed 200 OK in 5212ms (Views: 2679.7ms | ActiveRecord: 147.7ms)

I don't understand how the 2.6 seconds can be spent in the "views" when I'm not rendering to a view file, or how 5212ms can be spent in total. What's taking so much time, and how would one go about speeding things up?

Edit: There are about 1000 books returned in this particular request, and I'd guess each is about 1kb of data. Edit 2: Looking at the response in the console, the size of the response is 973kb.

Upvotes: 5

Views: 2239

Answers (3)

John Naegle
John Naegle

Reputation: 8247

Once you've preloaded all your models that are used to render the view, you can optimize the generation of the JSON. What you have above (render :json => {:books => books}) is not very fast.

Take a look at this question: What is the fastest way to render json in rails

And consider switching to a different way of rendering JSON.

Upvotes: 0

Adrien
Adrien

Reputation: 725

Have you tried oj for a faster json generation ? According to its author:

So far is has achieved that at about 2 time faster than Yajl for parsing and 3 or more times faster writing JSON.

Maybe a good solution ?

Upvotes: 2

Drew
Drew

Reputation: 2663

See Chapter 1.3 Retrieving Multiple Objects in Batches: http://goo.gl/UR5B.

Also, you might want to look into eager loading the records.

Upvotes: 1

Related Questions