Rails - JSON encoding performance analysis
Scrutinize problem piece of code -
Rather than using Ruby array manipulation functions on activerecord objects fetched, try to use the sql filter, order, group etc. via AREL
at = User.arel_table
at1 = Object2.includes(:class3).where(at[:attribute1].lower.matches("%#{search_text.downcase}%"))
2. While querying, include all the nested objects for eager loading. Dramatic difference it makes -
users = User.includes(:addresses => [{:countries => :city}, :designations]).where('id in (?) AND active = 1', user_ids)
3. Now optimize the json encoding process -
Use Yajl library. Install like so
# Gemfile
gem 'yajl-ruby', :require => "yajl"
Use Yajl library
Ensure the engine used :
> MultiJson.engine
Installation might give an error about Notifier, update your ruby gems -
gem update --system
4. Other JSON builders could also be chosen -
Representative
Tokamak
Builder
JSONify
Argonaut
JSON Builder
RABL
References:
https://groups.google.com/forum/?fromgroups=#!topic/rails-oceania/kGHfiHU3GG4
http://stackoverflow.com/questions/10451722/what-is-the-fastest-way-to-render-json-in-rails
Use Yajl library for JSON processing -
# Gemfile gem 'yajl-ruby', :require => "yajl"
Options
https://github.com/mdub/representative
https://github.com/inem/tequila https://github.com/abril/tokamak https://github.com/jbr/argonaut
http://engineering.gomiso.com/2011/05/16/if-youre-using-to_json-youre-doing-it-wrong/
















