Ruby Memory Management

后端 未结 5 1857
遥遥无期
遥遥无期 2020-12-23 21:32

I have been using Ruby for a while now and I find, for bigger projects, it can take up a fair amount of memory. What are some best practices for reducing memory usage in Ru

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-23 22:09

    Beware of C extensions which allocate large chunks of memory themselves.

    As an example, when you load an image using RMagick, the entire bitmap gets loaded into memory inside the ruby process. This may be 30 meg or so depending on the size of the image.
    However, most of this memory has been allocated by RMagick itself. All ruby knows about is a wrapper object, which is tiny(1).
    Ruby only thinks it's holding onto a tiny amount of memory, so it won't bother running the GC. In actual fact it's holding onto 30 meg.
    If you loop over a say 10 images, you can run yourself out of memory really fast.

    The preferred solution is to manually tell the C library to clean up the memory itself - RMagick has a destroy! method which does this. If your library doesn't however, you may need to forcibly run the GC yourself, even though this is generally discouraged.

    (1): Ruby C extensions have callbacks which will get run when the ruby runtime decides to free them, so the memory will eventually be successfully freed at some point, just perhaps not soon enough.

提交回复
热议问题