Why does Ruby release memory only sometimes?

前端 未结 1 371
逝去的感伤
逝去的感伤 2021-01-13 20:46

Depending on how I generate a string Ruby will release the memory to the OS or it won\'t. The first test code will take up about 235MB

size = 2**22
string =          


        
1条回答
  •  一个人的身影
    2021-01-13 21:15

    Ruby MRI does not release memory back to the OS.

    Here's what I see with Ruby MRI 2.2 on OSX 10.10, using typical ps -o rss:

    • Allocating the big string by using * uses ~220MB.

    • Allocating the big string by using map uses ~340MB.

    On my system, the GC.start doesn't do anything to the RSS. In other words, I see the RAM usage stay the same.

    Notably, the map is using a lot of RAM:

    • (0...size).map{ '' } uses ~300MB.

    When I loop your examples, something interesting emerges:

    • Allocating the big string by using * continues to use the same RAM, i.e. RSS doesn't change much.

    • Allocating the big string by using map grows by ~40M per loop.

    • Doing just (0...size).map{ '' } grows by ~40M per loop.

    This shows me that Ruby map may have a RAM-related issue. It's not exactly a problem, because Ruby isn't raising NoMemoryException, but does seem to be a non-optimal use of RAM.

    0 讨论(0)
提交回复
热议问题