本文介绍了Ruby / Rails垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于http是无状态的,所以对应用程序的每个请求都会创建一个新对象。 Rails如何清理未使用的对象/多频繁?

解决方案

简单的回答:Ruby运行时有一个垃圾收集器。根据运行时间(JRuby / JVM世代GC,IronRuby / CLR世代GC,经典Ruby /标记扫描GC),使用不同的算法。但基本要求非常简单:


  • 如果有可用空间不足的分配请求 - 有多少不足是GC算法的组成部分 - 然后开始GC

  • GC通过扫描开始,它是全局变量和堆栈位置(参数和局部变量) ,发现哪些物体还活着;它标记它找到的每个对象然后,GC进程查看这些对象内的链接(引用),并递归到那些尚未标记的对象中。

  • 然后,GC可以开始移动/复制所有标记的对象,以便将它们压缩到内存中。
  • 将新分配发生的空闲指针重置为
  • 如果仍有可用内存不足,则从操作系统分配更多内容

  • 所有旧对象在扫描过程中未标记为垃圾,并通过复制过程和重置空闲指针隐式丢弃。
  • 收集频率取决于可能受操作系统,物理内存量,操作系统内存压力,用户控制调整,底层平台版本修订版,动态优化段米等等。尽管事情变得越来越复杂,代代相传的收藏家可能会感到更加复杂,但其中的大部分内容都归结于这个不足的自由记忆测试的位置。


    Since http is stateless, every request to an app creates a new object. How does Rails clean up the unused objects / how frequently?

    解决方案

    Simple answer: the Ruby runtime has a garbage collector. Depending on the runtime (JRuby/JVM generational GC, IronRuby/CLR generational GC, classic Ruby/mark-sweep GC) different algorithms are used. But the basics are pretty simple:

    • Upon an allocation request if there is "insufficient free memory" available - how much is insufficient is one of the ingredients of the GC algorithm - then a GC will commence
    • The GC starts by scanning roots, which are global variables and stack locations (parameters and local variables), to discover which objects are still alive; it marks each object it finds
    • Then, the GC process looks at links (references) inside these objects, and recurses into those objects that haven't already been marked
    • The GC can then start moving / copying all marked objects so that they are compacted in memory
    • The "free pointer", from whence new allocations occur, is reset to the end of this compacted chunk of memory
    • If there is still "insufficient free memory", then more is allocated from the operating system
    • All old objects that weren't marked during the scanning process are garbage and are implicitly discarded through the copying process and resetting of the free pointer.

    The frequency of collections depends on the tuning of the GC, which may be affected by the operating system, the amount of physical memory, operating system memory pressure, user-controlled tweaks, underlying platform version revisions, dynamically optimized parameters, etc. Much of it comes down to deciding where the bar lies in that "insufficient free memory" test, though things get more complicated with generational collectors.

    这篇关于Ruby / Rails垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 23:37