Rendering JSON is pretty easy in Rails.
1
|
|
It works well if there are small number of records to be returned. But what happens when we need to return 10,000 records at once? Things slow down dramatically and the most time-consuming parts are JSON serialization and database operations.
Include only Required Attributes
The first obvious thing is generating JSON with only attributes that we need.
1
|
|
Tidying JSON gives over 20% performance
1 2 |
|
Select only Required Columns
Second, we should consider selecting only required columns when we don’t need all of them.
1
|
|
It’ll help us to avoid transferring a huge amount of data to the application from the database and gives 2x speed up.
1 2 3 |
|
Don’t Instantiate ActiveRecord Objects If Possible
Let’s implement a method to return “lightning” array of hashes instead of ActiveRecord instances.
1 2 3 4 5 6 7 |
|
Returns array of hashes instead of array of single column values. Invoke a new method in controller.
1
|
|
Using lightweight hashes makes JSON rendering 2x faster.
1 2 3 4 |
|
Fastest JSON
There are several JSON libraries available:
- JSON - The default JSON gem with C-extensions (ships with Ruby 1.9).
- YAJL - Yet Another JSON Library.
- OJ - Optimized JSON.
It’s a good idea to use the fastest dumper of them.
1 2 3 |
|
But we prefer active_model_serializers which it run faster than OJ.
Summarized benchmark results are:
1 2 3 4 5 6 7 8 9 |
|
So far so good, That’s it!!! See ya!!! :)