closure

  • Closure definition: When an internal function is saved to the outside, a closure is generated, which causes the original scope chain to not be released, resulting in a memory leak.
  • Closure benefits:
    • Variables reside in memory for a long time
    • Avoid contaminating global variables
    • Private members exist
  • Disadvantages of closures:
    • Increase memory usage
    • Prone to memory leaks
  • Functions/usage scenarios of closures
    • Implement common variable = “do the accumulator
      • Code implementation
        function add() {
            var count = 0;
            function demo() {
                count ++;
                console.log(count);
            }
            return demo;
        }
        var counter = add();
        counter();
        counter();
        Copy the code
    • You can do caching
      • Code implementation
        function eater() {
            var food = '';
            var obj = {
                eat: function() {
                    console.log('i am eating' + ' ' + food);
                    food = '';
                },
                push: function(myFood) {
                    food = myFood;
                }
            }
            return obj;
        }
        var eater1 = eater();
        eater1.push('banana');
        eater1.eater();
        Copy the code
    • Encapsulation attributes can be privatized
      • Code implementation
        function Hang(name, wife) {
            var prepareWife = 'xiaozhang';
            this.name = name;
            this.wife = wife;
            this.divorce = function() {
                this.wife = prepareWife;
            }
            this.changePrepareWife = function(target) {
                prepareWife = target;
            }
            this.sayPrepareWife = function() {
                console.log(prepareWife);
            }
        }
        var deng = new Hang('deng', 'xiaoliu');
        deng.prepareWife;
        deng.sayPrepareWife();
        Copy the code
  • Closure defense
    • Closures can cause multiple executing functions to share a common variable, and you should try to prevent this from happening unless there is a special need.
  • Solutions to closures
    • Use immediate execution functions

Execute function immediately

  • Execute immediately function definition: this type of function is undeclared and released after a single execution, suitable for initialization.
  • The difference between an immediate function and a normal function is that the immediate function is released as soon as it completes execution

A memory leak

  • Memory leak definition: when the application no longer needs the memory, for some reason, the memory has not been reclaimed by the operating system or the available memory pool.
  • Examples of memory leaks:
    • Unexpected global variables
      • Assigning values to undeclared variables in a function creates a new variable in the global object.
        function bar() { say = 'hehe'; Function bar() {window.say ='hehe'; }Copy the code
      • Or create a global variable using this
        function foo() {
            this.name = 'hehe';
        }
        foo();
        Copy the code
    • Forgotten timer or callback function
      • The use of timer setInterval() is not cleared, and in older versions of IE6, circular references are not handled, causing memory leaks.
    • Out of the DOM reference
    • closure
  • How to identify memory leaks
    • Chrome
      • Timeline
      • Profiles
    • Node
  • How to solve
    • Hand release
      • Code implementation
        var arr = [1.2.3];
        arr = null;
        Copy the code
    • Using weak references (WeakSet and WeakMap)
      • Advantages: A WeakMap reference to an Element is a weak reference and is not counted in the garbage collection mechanism. This means that once a reference to the node is removed, its memory footprint is freed by the garbage collection mechanism. The key value pair saved by WeakMap will also disappear automatically.
      • Code implementation
        const vm = new WeakMap();
        const element = document.getElementById('example');
        vm.set(element, 'something');
        vm.get(element);
        Copy the code

Garbage collection mechanism

  • Definition:
    • Find garbage in memory space.
    • Recycle garbage so that programmers can reuse that space.
  • Common garbage collection algorithms
    • Reference counting method
      • Definition: Track how many times each value is referenced.
      • Advantages:
        • Immediate recycling: When the referenced value is 0, the object immediately connects itself to the free list as free space. That is, it is recycled as soon as it becomes garbage.
        • Because even with the collection, the program does not pause to use the GC alone for a long period of time, the maximum pause time is short.
        • You don’t have to go through all the live and inactive objects in the heap.
      • Disadvantages:
        • Counters need a lot of space: because you can’t predict the upper limit of references, for example, it’s possible to have 32 bits (2 ^ 32) of objects referencing an object at the same time, so timers need 32 bits.
        • The biggest disadvantage is that it can’t solve the problem that circular references can’t be recycled, which is the previous problem of IE.
      • Code sample
        var a = new Object();
        var b = a;
        a = null;
        b = null;
        Copy the code
    • Tag cleanup (most used in V8 engines)
      • Definition:
        • Mark phase: Mark all active objects
        • Purge phase: Destroy unmarked (that is, inactive) objects
      • Advantages:
        • Simple implementation, marking with a binary can be expressed
        • Fixed the problem of circular references
      • Disadvantages:
        • Cause fragmentation (somewhat similar to disk fragmentation)
        • If a block size is not found, the free linked list (the list of addresses that hold all the free address Spaces in the heap) is traversed all the way to the end.
    • Replication algorithm
      • Divide a memory space into two parts, called From space and To space. Of these two Spaces, one must be used and the other free. The newly allocated objects are put into the From space, and when the From space is full, the new generation of GC starts. The algorithm checks for surviving objects in the From space and copies them To the To space. If inactivated objects are destroyed, the From, To, and To Spaces are swapped when the assignment is complete, and the GC is finished.
  • Reduce garbage collection in JavaScript
    • Object to optimize
      • Maximum reuse of objects, do not set to null as much as possible, as soon as possible garbage collection.
        var obj = {}; for(var i = 0; i < 10; i++) { // var obj = {}; // This creates an object each time obj.age = 19; obj.name = 'hehe'; console.log(obj); }Copy the code
    • Array optimization
      • Assigning [] to an array object is a shortcut to emptying the array, but it creates a new empty object and turns the original array object into a small piece of memory garbage.
        var arr = [1, 2, 3];
        arr = [];
        Copy the code
      • Setting the length of the array to 0 also clears the array, and at the same time reuses the array and reduces memory garbage.
        var arr = [1.2.3];
        arr.length = 0;
        Copy the code
    • Method function optimization
      • For example, in the main loop of a game, it is common for setTimout or requestAnimationFrame to call a member method. Each call returns a new method object, which results in a lot of method object garbage. To get around this method, you can save the method as the return value.
        function say() { console.log('hehe'); } setTimeout((function(self) { return function() { self.say(); SayFunc = (function(self) {return function() {self.say(); } })(this); setTimout(this.sayFunc, 16)Copy the code

Your praise is my continuous output of power, I hope to help everyone, learn from each other, if you have any questions, please leave a message below, be sure to reply!!