Memory management

Why is memory managed?

function fn() { arrList = []
arrList[100000] = 'lg is a coder' }
fn()
Copy the code

For example, when executing this code, memory usage will continue to rise, causing memory leaks

  1. Let obj = {}
  2. Obj. name = ‘lg’
  3. Free space obj = null

GC garbage collection mechanism

If the call completes without a reference, it should be reclaimed

Reference counting algorithm

  • Core idea: set the number of references, judge the current number of references is 0, then garbage collection
  • Reference counter
  • Modify the reference number when the reference relationship changes

Advantages:

  • Recycle garbage immediately
  • Minimize program pauses

Disadvantages:

  • A circular reference object cannot be recycled
function fn() {
    const obj1 = {}
    const obj2 = {}
    
    obj1.name = obj2
    obj2.name = obj1
    
    return 'asdas'
}

fn()
Copy the code

So at this point, even though the function is done, there are references to obj2 in obj1, and references to obj1 in obj2. Circular reference, resulting in garbage can not be collected

  • Time consuming

Common performance optimization methods

  • Try not to use global variables. You can cache global variables.
  • If a constructor has member methods inside it, they need to be called frequently later. By adding methods to prototype objects, you can achieve significant performance savings over adding them directly inside the constructor.
  • Avoid closures pitfalls:
function foo() {
    var el = document.getElementById('btn')
    el.onclick = function() {
        console.log(el.id)
    }
    // el = null
}
foo()
Copy the code

If BTN is already in the DOM and we refer to it again via el assignment, we get two references. At this point, if the DOM node is removed, the V8 engine’s garbage collection mechanism will not be able to reclaim it because there are still references to closures.

Solution: Assign null to free reference space after use

  • The for loop can be defined as a variable to avoid fetching the array length each time
const arr = [1.2.3.4.5]
for(let i = 0, len = arr.length; i < length; i++) {
    console.log(i)
}
Copy the code
  • Choose the optimal loop structure: forEach > for > forin

Document fragmentation node can be added as follows:

const fragEle = document.creatDocumentFragment()
for(var i = 0; i < 10; i++) {
    var oP = document.creatElemnt('p')
    oP.innerHTML = i
    fragEle.appendChild(oP)
}
// Wait for execution to complete and add it to the body in one go
document.body.appendChild(fragEle)
Copy the code
  • If the nodes are existing in the document, clone them to reduce performance
for(let i = 0; i < 3; i++) {
    let newP = oldP.cloneNode(false)
    newP.innerHTML = i
    document.body.appendChild(newP)
}
Copy the code

Replace the new Object with a literal

// let a1 = new Array(3)
// a1[0] = 1
// a2[1] = 2
// a3[2] = 3

let a = [1.2.3]
Copy the code