How do I check ActiveRecord memory usage?

Asked 3 months ago, Updated 3 months ago, 11 views

As for ActiveRecord for rails, I think it caches SQL query results.

In the log, click

Model name Load (0.8ms) SELECT and below

Save the and Load to cache and display the query execution time.

CACHE (0.1ms) SELECT and below

indicates that it was retrieved from the cache and also shows how long it took to retrieve it from the cache.

I understand that
So, is it not possible to display the amount of memory being cached?
It doesn't matter if it's not logged, it can be checked every time.

ruby-on-rails rails-activerecord

2022-09-30 14:21

2 Answers

If you insert middleware like this, it will come off.

class QueryCacheProf
  def initialize (app)

  def call(env)
    @ do
      memsize_of_query_cache = memsize_of_all_before_query_cache_cleared-ObjectSpace.memsize_of_all "memsize of query cache: #{memsize_of_query_cache}"

Rails.application.config.middleware.insert_after ActiveRecord::QueryCache, QueryCacheProf

If you run bundle execrake middleware, you will see the line use ActiveRecord::QueryCache.

In the Rack middleware that ActiveRecord plugs into, this middleware caches the results of the same query being requested.

Specifically, the following parts are inserted.,L20

Specifically, if you read the QueryCache middleware implementation, you can call connection.enable_query_cache! and then process the request.

After calling enable_query_cache!, @query_cache_enabled is set to

If @query_cache_enabled is configured, the results of the select statement are cached in cache_sql.,L68

If you read cache_sql, you will see that @query_cache has cached the results.
If you measure the size of the cache here, you will see how much memory you are consuming.

2022-09-30 14:21

"If you google with the keyword ""ruby memory profiler"", you will get a lot of information."

I've never used it before, so I can't show you how to do it, but if you look at the sources above, you may get answers to the questions.

2022-09-30 14:21

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.