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 
3
  • What problem are you really trying to solve? (Or are you just curious about the inner workings of Ruby/Rails?) Commented Aug 24, 2014 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? Commented Aug 24, 2014 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. Commented Aug 24, 2014 at 17:26

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.