I'm optimizing some slow transactions in our Rails application and a I see significant time spent rendering JSON views:
Rendered welcome/index.json.rabl (490.5ms) Completed 200 OK in 1174ms (Views: 479.6ms | ActiveRecord: 27.8ms)
Assuming that the API call is returning exactly the data it needs to return, What is the fastest way to render JSON in rails?
We are using Rabl because of the ability to share code easily, but we aren't tied to it.
render :json essentially calls to_json and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback option to specify the name of the callback you would like to call via JSONP.
What is JSON? JSON is short for Javascript Object Notation. It is the simplest and easiest way to transfer data using the internet which makes the language extremely popular for APIs, enabling developers to work across multiple languages.
Currently oj seems to be the fastest renderer - beating yajl (according to the oj author's comparison).
Oj is used by default in the latest multi_json (and rails uses mutli_json by default), so swapping to oj should be as simple as adding the following to your Gemfile:
# Gemfile gem "oj"
Then each time you call render, it will now use oj.
render :json => { ... } # uses multi_json which uses oj
Oj also provides additional specific interfaces, if you want even more performance, but sticking to multi_json makes it easier to swap out gems in the future.
Note that if you have any { ... }.to_json
calls - these will not be upgraded to use oj unless you call Oj.mimic_JSON
in an initializer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With