Best practices for reducing Garbage Collector activity in Javascript

后端 未结 4 1521
渐次进展
渐次进展 2020-11-29 14:32

I have a fairly complex Javascript app, which has a main loop that is called 60 times per second. There seems to be a lot of garbage collection going on (based on the \'saw

4条回答
  •  半阙折子戏
    2020-11-29 15:31

    As a general principle you'd want to cache as much as possible and do as little creating and destroying for each run of your loop.

    The first thing that pops in my head is to reduce the use of anonymous functions (if you have any) inside your main loop. Also it'd be easy to fall into the trap of creating and destroying objects that are passed into other functions. I'm by no means a javascript expert, but I would imagine that this:

    var options = {var1: value1, var2: value2, ChangingVariable: value3};
    function loopfunc()
    {
        //do something
    }
    
    while(true)
    {
        $.each(listofthings, loopfunc);
    
        options.ChangingVariable = newvalue;
        someOtherFunction(options);
    }
    

    would run much faster than this:

    while(true)
    {
        $.each(listofthings, function(){
            //do something on the list
        });
    
        someOtherFunction({
            var1: value1,
            var2: value2,
            ChangingVariable: newvalue
        });
    }
    

    Is there ever any downtime for your program? Maybe you need it to run smoothly for a second or two (e.g. for an animation) and then it has more time to process? If this is the case I could see taking objects that would normally be garbage collected throughout the animation and keeping a reference to them in some global object. Then when the animation ends you can clear all the references and let the garbage collector do it's work.

    Sorry if this is all a bit trivial compared to what you've already tried and thought of.

提交回复
热议问题