3
  • I want to know how much memory is consumed if I create a ruby object. Does Ruby have any method to tell?
  • Is there any difference for memory consumption in the following?

    users = User.where("created_at > ?", 2.months.ago)  # select all fields
    users = User.select(:user_name).where("created_at > ?", 2.months.ago) # just select one field
    
sawa
  • 165,429
  • 45
  • 277
  • 381
pangpang
  • 8,581
  • 11
  • 60
  • 96
  • What problem are you really trying to solve? (Or are you just curious about the inner workings of Ruby/Rails?) – RyanWilcox Aug 24 '14 at 15:34
  • I just curious about it. If ‘users’ variable is an 100,000 elements array, will it consume much memory or not, should we avoid to do this? – pangpang Aug 24 '14 at 16:19
  • 1
    Some of this depends on what you do with the query (it's not executed until AR thinks it really has it). If you're doing `Users.where(...).to_a` and getting those records as an array, yes that may be bad news if you have 100,000 records. There are methods in AR to help with this: find_each is one of those methods so you DON'T create 100,000+ Ruby objects to - say - iterate over your big users list. – RyanWilcox Aug 24 '14 at 17:26

2 Answers2

5

You could use ruby-prof, a wonderful ruby profiler that will tell you everything your code is doing, including memory allocation. The usage is really simple:

require 'ruby-prof'

# Profile the code
result = RubyProf.profile do
  ...
  [code to profile]
  ...
end

# Print a flat profile to text
printer = RubyProf::FlatPrinter.new(result)
printer.print(STDOUT)

It can output results as text, text graph, html graph, call stack and more. In the readme there is also a section about profiling rails applications. The installation is immediate, so give it a try:

gem install ruby-prof
enrico.bacis
  • 30,497
  • 10
  • 86
  • 115
3
  • Firstly there's no easy way to measure how much memory an object consumes. If it's a Rails App you can use this Unix Script to check. Also there's a great blog post that may help you about this issue.

  • In your second question. The 2nd query is probably gonna consume less memory since ActiveRecord isnt processing all the fields to build an AR object. Ultimately it's better to use .pluck for you second query.

    users = User.where("created_at > ?", 2.months.ago).pluck(:user_name)

Community
  • 1
  • 1
Serdar Dogruyol
  • 5,147
  • 3
  • 24
  • 32