Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Javascript Garbage Collection when making function returns

Am I right in thinking that,

  1. With each call, test() exports another new object that must be garbage collected later.

    var sumValue=test(0,3);
    
    function test(startingValue,n){
        return({sum:startingValue+n});
    }
    
  2. This version of test() requires no garbage collection later.

    var sumValue={sum:0};
    test(sumValue,3);
    
    function test(output,n){
        output.sum+=n;
    }
    
like image 913
JustAsking Avatar asked Sep 12 '26 08:09

JustAsking


1 Answers

  1. Yes, on each call it will create a new object.
  2. Yes, since you're just mutating the existing object.

For this specific case, I wouldn't worry about it. It's too small to make an impact (unless this code is being run multiple times for extended periods).

like image 181
Joseph Avatar answered Sep 14 '26 20:09

Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!