📜 ⬆️ ⬇️

How we increased JSON generation speed by 6000 times

A brief overview of how to generate JSON

Today Rails has the following methods for serializing objects in JSON:
  1. Call to_json () directly.
  2. Rable
  3. Active model serializers
  4. Jbuilder


The first method is ideal for situations where you do not need to serialize nested objects.
@posts.to_json(:include => [...], :methods => [...]) 

However, forming a JSON response with a list of models, it becomes necessary to serialize the associated models in the desired form.

Jbuilder
From personal experience, the most organically fit into a Rails development is, included by default in Rails 4, JBuilder.
 json.extract! message, :id, :content, :chat_id json.user do json.cache!(["user_", message.user_id]) do json.partial! 'users/user', user: message.user end end 

Rable
RABL, compared to other gems, seems to be an ancient monster because of its syntax and slow to do so.
 collection :@messages attributes :id, :content, :chat_id child(:user) { attributes :name } node(:read) { |message| message.read_by?(@user) } 


ActiveModel :: Serializer
Active model serializers proposes to describe JSON in the form of ruby ​​classes, without invented syntax, which reduces the zoo's use of different DSL in the project.
')
Solving performance problems

Small comparison

Test data: 1000 typical messages with the sender and additional fields.
Json:
 { 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: "Ivan Petrov", image: "https://lh6.googleusercontent.com/photo.jpg" }, files: [ ], links: [ ] } 


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

The numbers are averaged, but the overall picture is clear. It makes no sense to compare different gems among themselves, since the difference is not significant, but objectively, JBuilder is the fastest today.
For convenience you have to pay speed. All the described gems in speed lose the to_json () method several times.
Using JBuilder without configuration will cost you ~ 600.0ms

There are several ways to speed up JBuilder:



In the Staply project (almost open beta) we used JBuilder only at the initial stage of development, gradually switching to the formation of JSON manually using to_json (). What is the olnichno demonstration of the entire concept of Rails, providing a fairly quick and easy development at the beginning with optimization at the end.

Source: https://habr.com/ru/post/226725/


All Articles