Note that there are some explanatory texts on larger screens.

plurals
  1. PORails & Memcached: Optimizing multiple fetches
    primarykey
    data
    text
    <p>I am building a Rails backend to an iPhone app.</p> <p>After profiling my application, I have found the following call to be especially expensive in terms of performance:</p> <pre><code>@messages.as_json </code></pre> <p>This call returns about 30 message objects, each including many child records. As you can see, a single message json response may make many DB calls to be composed:</p> <pre><code> def as_json(options={}) super(:only =&gt; [...], :include =&gt; { :user =&gt; {...}, :checkin =&gt; {...} }}, :likes =&gt; {:only =&gt; [...], :include =&gt; { :user =&gt; {...] }}}, :comments =&gt; {:only =&gt; [...], :include =&gt; { :user =&gt; {:only =&gt; [...] }}} }, :methods =&gt; :top_highlight) end </code></pre> <p>On average the <code>@messages.as_json</code>call (all 30 objects) takes almost 1100ms.</p> <p>Wanting to optimize I've employed memcached. With the solution below, when all my message objects are in cache, average response is now 200-300ms. I'm happy with this, but the issue I have is that this has made cache miss scenarios even slower. In cases where nothing is in cache, it now takes over 2000ms to compute.</p> <pre><code> # Note: @messages has the 30 message objects in it, but none of the child records have been grabbed @messages.each_with_index do |m, i| @messages[i] = Rails.cache.fetch("message/#{m.id}/#{m.updated_at.to_i}") do m.as_json end end </code></pre> <p>I understand that there will have to be some overhead to check the cache for each object. But I'm guessing there is a more efficient way to do it than the way I am now, which is basically serially, one-by-one. Any pointers on making this more efficient?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload