Search code examples
ruby-on-rails-4to-json

Slow to_json with oj gem in Rails 4.2


I upgraded my Rails app from Rails 3.2 to Rails 4.2. The to_json performance in my views is terrible. In my Rails 3.2 app I used multi_json and the Oj gem to get great performance. With Rails 4.2 I setup the oj gem this way:

gem 'oj', '~> 2.14', '>= 2.14.2'
gem 'oj_mimic_json', '~> 1.0', '>= 1.0.1'

However, the to_json performance doesn't seem to be nearly as good as with the Rails 3.2 app. One to_json call takes about 50% of CPU time.

The Oj gem documentation mentions adding:

serialize :metadata, Oj

to make it work with ActiveRecord. Is this line supposed to go in the models that I use?

enter image description here


Solution

  • I found answer mentioned here: https://github.com/ohler55/oj/issues/199

    After adding both gems, one also has to call:

    Oj.mimic_JSON()
    

    For .to_json to use Oj.