What is the fastest way to render json in rails

I am optimizing some of the slow transactions in our Rails application, and I can see a significant amount of time spent rendering JSON views:

Rendered welcome/index.json.rabl (490.5ms) Completed 200 OK in 1174ms (Views: 479.6ms | ActiveRecord: 27.8ms) 

Assuming the API call returns exactly the data it needs to return, What is the fastest way to render JSON in rails?

We use Rabl because of the ability to easily share code, but we are not attached to it.

+42
json ruby-on-rails ruby-on-rails-3
May 4 '12 at
source share
3 answers

Rabl uses multi_json for cross-platform compatibility, and by default does not use the pretty fast yajl library. Rabl configuration documentation explains the solution:

 # Gemfile gem 'yajl-ruby', :require => "yajl" 

In case it is still not enough, it is enough to study another JSON serializer, for example oj . You can also render the tool and see where the bottleneck is.

+14
May 4 '12 at 3:36
source share

Currently oj seems to be the fastest visualization tool - beating yajl (according to oj author comparison ).

Oj is used by default in the last multi_json file (and rails uses mutli_json by default), so replacing with oj should be as simple as adding the following to your Gemfile:

  # Gemfile gem "oj" 

Then every time you invoke the render, it now uses oj.

  render :json => { ... } # uses multi_json which uses oj 

Oj also provides additional custom interfaces if you want even more performance, but sticking to multi_json makes it easy to replace gems in the future.

Please note that if you have any calls { ... }.to_json , they will not be updated to use oj unless you call Oj.mimic_JSON in the initializer.

+40
May 9 '12 at 4:01
source share

Rails 3 uses multi_json, but uses it only for json decoding, not for encoding . Json encoding / rendering / generation uses the ActiveSupport JSON to_json , so it is always slow (even if you use Oj gem).

You can explicitly render with multi_json by doing:

 render :json => MultiJson.dump(@posts) 

Or you can try the rails-patch-json-encode gem (for me), which will use multi_json by default. This will affect all the built-in to_json methods, so make sure all tests pass.

+12
Oct 07 '13 at 7:37
source share



All Articles