Rendering JSON is pretty easy in Rails:
1
|
|
This 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, e.g.:
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 speedup:
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 |
|
It works the same way as pluck but 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 |
|
Use the fastest JSON dumper
There are several JSON libraries available:
- JSON The default JSON gem with C-extensions (ships with Ruby 1.9)
- Yajl Yet Another JSON Library by Brian Lopez
- Oj Optimized JSON by Peter Ohler
It’s a good idea to use the fastest dumper of them:
1 2 3 |
|
So we prefer using Oj dumper:
1
|
|
Summarized benchmark results are:
1 2 3 4 5 6 7 8 |
|