Ruby GC execution exceeding ~250-320ms per request

前端 未结 4 2022
暗喜
暗喜 2021-02-04 09:18

I have a ruby on rails application. I am investigating an Apdex decline in my NewRelic portal and I\'m seeing that on average, 250-320ms of time is being spent on GC execution.

4条回答
  •  粉色の甜心
    2021-02-04 09:38

    You should use an allocation tracer to find out where your code is allocating objects, and how many. I've used memprof in the past with great results... the big drawback is that it only works under Ruby 1.8 (hopefully your code is 1.8.7-compatible).

    If you can run your application under Ruby 1.8.7, then install the "memprof" gem, and:

    require 'memprof'
    GC.disable
    Memprof.track { run_test_code_here }
    

    That will print a listing of allocated object counts (grouped both by class and by the source line where the allocation occurred) to standard output.

    When you have problems with excessive time being spent in the garbage collector, usually an allocation trace reveals one or two places where your program is allocating tons of objects. It's impossible to say in advance what the solution will be, but often it will involve either:

    1. caching results to avoid repeated calculations,
    2. using destructive operations where it is safe to do so (like map! instead of map),
    3. reusing a temporary object in a loop (resetting its state each time) rather than allocating a new one on each iteration, or
    4. avoiding the use of string constants (or array/hash literals) in a loop which is executed many times (a new object will be allocated on each iteration).

提交回复
热议问题