Ruby on Rails: serializing Hash is incredibly slow

I have a simple model called "Search" used to store queries. It captures the URL parameters and stores them in the attribute: search_criteria, which serializes as a hash:

serialize :search_criteria, Hash 

It all works fine, but it does awful. For a total of 5 objects, the following statements take approximately 0.2 seconds.

 start = Time.now SavedSearch.all.map(&:search_criteria) puts Time.now - start 

If, however, I delete the serialization string (such that search_criteria returns the string), the operators take only 0.002 seconds. This is a 2 order difference for hash deserialization !!

What's going on here?

Rails.version = 3.2.8 Ruby 1.9.3p194 (2012-04-20 version 35410) [x86_64-linux]

+4
source share
2 answers

The problem is caused by the YAML parser. Deserializing YAML is incredibly slow. I solved this by serializing the search_criteria hash as JSON, not YAML. Now it works 100 times faster.

For some additional reading material, see http://iprog.com/posting/2009/10/ruby-on-rails-performance-series-intro-yaml

+2
source

An active recording is probably associated with a lot of overhead, and this seems to be superfluous. As it loops, it creates an instance of each object in SavedSearch, and then evaluates the attributes that it needs to create, then it makes a map.

If you know the exact structure that seems to be stored in 'search_criteria', just store it in YAML in a text attribute. It should be much faster.

+1
source

Source: https://habr.com/ru/post/1444851/


All Articles