0
$ ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]
$ irb

Memory usage right after IRB starts: 56MB

>> a = []
>> 1000.times { a << (1..50000).to_a.map { |i| "abc" }.join }
>> a = nil

Memory usage now: 244MB (as expected)

>> GC.start

Memory usage now: 146MB

Where did the rest of the memory go and why hasn't it been freed by the garbage collector?

user513951
  • 12,445
  • 7
  • 65
  • 82
Sergey
  • 4,702
  • 6
  • 26
  • 32
  • 2
    http://stackoverflow.com/questions/20385767/finding-the-cause-of-a-memory-leak-in-ruby/20608455#20608455 this is [almost] the same question, and the cause is exactly the same. Please let me know if you are OK with me marking this question as being a duplicate. – Aleksei Matiushkin Apr 09 '16 at 17:53
  • The question is a bit different but the answer is exactly the same. It's fine to mark it as a duplicate but I wasn't able to Google it so it may help someone to find it by this title even though the answer is the same. Seem that in short, there is simply is no way to make Ruby free the remaining memory and it will rather get killed. – Sergey Apr 09 '16 at 18:03
  • Marking a question as a duplicate does not hide it. – Aleksei Matiushkin Apr 10 '16 at 06:53

1 Answers1

0

A Ruby process doesn't just always use the exact amount of memory needed for the number of living objects. It allocates in chunks of a predetermined size, and releases the chunks some time after GC.

See http://www.sitepoint.com/ruby-uses-memory/.

When you have more objects being used than Ruby can fit into memory, it must allocate additional memory. Requesting memory from the operating system is an expensive operation, so Ruby tries to do it infrequently. Instead of asking for another few KB at a time, it allocates a larger chunk than it needs.

...

Ruby holds onto this allocated memory for some time, since allocating memory is expensive. If the process used that maximum amount of memory once, it can happen again. The Memory will be freed gradually, but slowly.

Community
  • 1
  • 1
user513951
  • 12,445
  • 7
  • 65
  • 82
  • What if you have only 256MB or memory available? Will Ruby rather get killed for being unable to allocate memory or will it free it at the last moment when more memory is really needed? – Sergey Apr 09 '16 at 17:52
  • This sounds like a new question. Like any process that uses too much memory, what happens to it depends on how your system is set up. It could start using swap memory, or the process could just crash. – user513951 Apr 09 '16 at 17:56