How we Increased the Speed of JSON Generation by 3000 Times

Grigorii Liubachev
2 min readJun 23, 2014


Short review of the JSON generation methods

As for today in Rails there are several ways to serialize the objects in JSON:

  1. Call to_json().
  2. RABL.
  3. Active model serialisers
  4. JBuilder

First way fits perfectly for the situations when it is not needed to serialize the nested object

@posts.to_json(:include => [...], :methods => [...])

However, when creating the JSON reply with the list of models, it is needed to serialize connected models in a proper way.


According to my own experience Jbuilder, that is included by default to the Rails 4, fits the Rails-development best of all.

json.extract! message, :id, :content, :chat_id
json.user do
json.cache!(["user_", message.user_id]) do
json.partial! 'users/user', user: message.user


RABL, compared to other gems, seems like an unproductive monster, mostly due to an seemingly outdated Syntax and clumsiness.

collection :@messages
attributes :id, :content, :chat_id
child(:user) { attributes :name }
node(:read) { |message| message.read_by?(@user) }


Active model serializers proposes to create JSON as ruby classes, without any made-up syntax. That lowers the madness of using different DSL in the project.

Solution of the productivity problem (Small comparison)

Test task: 1000 typical messages with the sender and some extra fields.


id: 1,
content: "Lorem",
chat_id: 1,
created_at: "2014-06-18T21:47:49.363Z",
kind: 0,
formatted_content: "<span>Lorem</span>",
user: {
id: 1,
name: "John Smith",
image: ""
files: [ ],
links: [ ]

to_json: 0.2 ms
JBuilder: 129.0 ms
JBuilder with OJ: 88.0 ms

Numbers are rounded, but the main point is clear. Comparing different gems between each other makes no sense, since the difference is not so significant, but objectively, JBuilder is the fastest as for today.

The price for comfort is speed. All the described gems by speed are far behind the to_json() method.

Usage of Jbuilder without settings would cost you ~600.0 ms

There are several ways to speed up JBuilder:

  • Connect gems: oj, oj_mimic_json, multi_json. Add the initialisation MultiJson.use( : oj ).That will substitute the standard stabiliser for the faster Oj
  • Not to use partials, that significantly slow down the Jbuilder. Long ago issues were created, but there, despite the closed status, this problem is basically not solved.
  • Cached templates using the built into the Jbuilder method cache!

In Staply we used Jbuilder only in the beggining of the development, gradually switching to forming the JSON manually with the help of to_json(). This is a great demonstration of the whole concept of Rails, that allows for quite fast and easy development in the start with the optimisation in the end.

(c) Maxim Indykov, 2014