Home  >  Q&A  >  body text

javascript - Why does the following code leak memory?

var theThing = null;
var replaceThing = function () {
  var originalThing = theThing;
  var unused = function () {
    if (originalThing)
      console.log("hi");
  };

  theThing = {
    longStr: new Array(1000000).join('*'),
    someMethod: function () {
      console.log(someMessage);
    }
  };
};

setInterval(replaceThing, 1000);

Question 1: The function declares the context when it is created, and updates the local variables in the scope chain when executed. The scope chain includes local variables inside the function when executed. What is more confusing is that the unused function is not When executing, how do you know that the unused function will definitely reference originalThing?
Question 2: How to explain this memory leak? I hope the experts can explain it in more detail?

phpcn_u1582phpcn_u15822734 days ago444

reply all(1)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:33:11

    • Question 1: After the variables in the function (replaceThing) leave its scope, if the function (replaceThing) is used once and is not referenced again until the program is executed, it will be recycled after a while.

    • Question 2: If you look at the thing assignment action, the action of creating an array is being done all the time. 1,000,000 join operations are performed at a time, and they are continuously executed. The speed of memory recycling cannot keep up with its growth rate, which will soon lead to memory leaks.

      theThing = {
        longStr: new Array(1000000).join('*'),
        someMethod: function () {
          console.log(someMessage);
        }
      };

    reply
    0
  • Cancelreply