Ruby on Rails with Grape: Performance comparison of JSON Serializers
Overview
In the Rails application we are working on, Rabl is used as JSON serializer. However, Rabl is very slow.
So I decided to compare with other serializers.
I often see articles that say“ActiveModel Serializer is overwhelmingly fast!”, But in most cases those articles tested serialization of single model. That test case does not match real world application.
You can not find performance comparisons that serialized JSON includes information on related models or include values calculated from model attributes.
Therefore, I tried comparing and examining the performance in a situation more suited to the reality. .
All players
The comparison target is as follows.
- Active_model_serializers: 0.10.6
- Grape-entity: 0.6.1
- Jbuilder: 2.7.0
- Rabl: 0.13.1
And used Ruby 2.4.1, Rail 5.1.3, Grape 1.0.0.
Sample application
Constitution
There are three models of User, Article, Bookmark. And these models have relations shown as below.
API
The existing API is an API for obtaining user information, and returns JSON as follows.
The attribute of User, the attribute of Article linked to that User, and whether Bookmark associated with each Article and User exist or not is represented by “is_bookmark”.
{
"user": {
"id": 1,
"name": "user0",
"articles": {
"id": 1,
"title": "title0",
"content": "content0",
"is_bookmarked": true"
}
}
}
Github repository
Https://github.com/k5trismegistus/grape-json-serializer-comparison
Tested on
The test environment is 13-inch Macbook Pro(2015).
Benchmark
Configuration
We have created 100 Users in advance, 1000 Articles (10 per User 1), 30000 Bookmarks (300 per User 1).
1000 number strings are randomly generated from the number contained in the User ID, and an API request is made using that ID.
I measured the number of seconds it took to field my request.
Result
| Serializer | Avg taken time per 1req |
|-------------------------|-------------------------|
| ActiveModel::Serializer | 97 [ms] |
| Grape::Entity | 77 [ms] |
| Jbuilder | 96 [ms] |
| Rabl | 102 [ms] |
Especially, Grape :: Entity is often remarkably earlier than others, and it seems to be nearly 20% faster as compared with Rabl.
ActiveModel :: Serializer which was reputed as very fast, seems not so fast as to say.
Although
Personally think that jbuilder is overwhelmingly easy to write JSON sturcture. If I do not have to care about performance so much, I choose Jbuilder.
Creating sample app, I felt that ease of using is following order.
Jbuilder >> Rabl> Grape :: Entity >>> ActiveModel :: Serializer
It is only my feeling.