Faster Rails JSON responses removing JBuilder and View rendering

On some Rails JSON api calls listing collections of items, I have been using jbuilder and jbuilder view partials to DRY out the code and it has been working well.

But on collection views, specially if they are complex and require a big amount of data per item, it takes quite some time and I thought maybe there is an alternative approach. There is: use POROs (Plain Old Ruby Objects). And it is almost twice as fast. Let me show you an example:

Imagine an app about movie reviews. People can review movies and others can “like” the review. An API call has to return some aggregated data about recent reviews:

  • rating
  • headline of the review
  • likes count
  • Some info about the author (name, avatar)
  • Some info about the movie reviewed (title, year, img)
  • Latest 3 likers (users) (name, avatar)

Using Jbuilder as per the documentation, I would do something similar to this:

Note: minimal model representation consists of the minimum attributes necessary to show in listings, as opposed to what will return a call to “/show” the concrete resource with a lot more verbose response.

It is faster to achieve the same result using Ruby objects that build in a Hash the desired representation:

Then the controller does not render a view, just converts to json the root component:

In the comparisons I have done I have used fake data constructed on the fly so the database access is left out of the equation.
You can find the full example rails application on my github repository and try for yourself.

  • This looks awesome! Do you have any benchmarks?

    • chipairon

      Hi Eric,
      You should do a benchmark yourself tailored to your specific needs to be a useful benchmark to you, but should be easy enough :)