In daily js writing process, we should start from each line of code, to improve speed, optimize performance. I’ve summarized some of the improvements in everyday code that you can make in terms of speed or performance when you’re doing a lot of code execution.

Performance Test site:

jsbench.me/

Be careful with global variables

Global variable features:

  • Global variables are defined in the global execution context, which is at the top of the scope and takes a lot of time to find

  • The global context remains on the context execution stack until the program exits and is not reclaimed

  • If a variable with the same name is defined in a local scope, the global variable will be obscured or contaminated

Point of optimization:

  • Reduce the scope chain lookup level
// example1
let i
for (i = 0; i < 1000; i++) {
 console.log(i)
} 
// example2 -- fastest
for (let i = 0; i < 1000; i++) {
  console.log(i)
} 
Copy the code

Caching global variables

  • For unavoidable global variables, global variables can be cached

Point of optimization:

  • Reduces the number of data reads (but consumes space)
// example1
function logInfo() {
  for (let i = 0; i < 1000; i++) {
   console.log(i)
  }
}
logInfo()
// example2 - fastest
function logInfo() {
  const log = console.log
  for (let i = 0; i < 1000; i++) {
   log(i)
  }
}
logInfo()
Copy the code

Methods needed to add an instance object to a prototype object

  • Methods in stereotype objects are shared, and methods in constructors are stored separately
// example1
let Fn1 = function () {
  this.foo = function() {
    console.log(1)}}let fn2 =  new Fn1() 

// example2 - fastest
let Fn2 = function () {}

Fn2.prototype.foo = function() {
  console.log(1)}let fn2 =  new Fn2()

Copy the code

Avoid the trap of closures

Features:

  • The outside has a reference to the inside

  • The outer scope accesses the variables of the inner scope

Disadvantages:

  • Closures are prone to memory leaks when used improperly

  • Don’t close for closure’s sake

Point of optimization:

  • Release variables when appropriate
 // example 1
 function foo () {
    let el = document.getElementById('btn')
    el.onclick = function() {
      console.log(el.id)
    }
  }
  // example 2 - better
  function foo () {
    let el = document.getElementById('btn')
    el.onclick = function() {
      console.log(el.id)
    }
    // Free up space
    el = null
  } 
Copy the code

Avoid using attribute access methods

  • JS does not require access methods for properties, so all properties are externally visible

  • Using attribute access methods only adds a redefinition without access control

// example1
function Person () {
  this.name = 'jill'
  this.age = 18
  this.getAge = function () {
    return this.age
  }
}

const p1 = new Person()
const age = p1.getAge() 

// example2 - fastest
function Person () {
  this.name = 'jill'
  this.age = 18
}

const p1 = new Person()
const age = p1.age 
Copy the code

conditional

1. Use switch instead of if-else for explicit conditional branches

  • If-else is easier to read with fewer conditions, but switch looks brighter with more code

  • In most cases switch is faster than if-else

2. Make sure the most likely scenario comes first

cycle

Optimizing for loops

1. Cache variables

<p class="btn">add</p>
<p class="btn">add</p>
<p class="btn">add</p>
<p class="btn">add</p>

// example1
const btns = document.getElementsByClassName('btn')

for (let i = 0; i < btns.length; i++) {
  console.log(i)
}
// example2 - fastest
const btns = document.getElementsByClassName('btn')

for (let i = 0, len = btns.length; i < len; i++) {
  console.log(i)
}
Copy the code

2. ForEach loop is adopted

// example1- slower
const arr = [1.3.2.4.1]
for (let key in arr) {
  console.log(key)
}
// example2- better
const arr = [1.3.2.4.1]
for(let i = 0, len = arr.length; i < len; i++) {
  console.log(i)
} 
// example3- fastest
const arr = [1.3.2.4.1]
arr.forEach((item, index) = > {
  console.log(index)
}) 
Copy the code

The while loop is better

// example1 
for (let i = 0; i < 10; i++) {console.log(i)
}
// example2- fastest
let i = 0
while(i < 10) {
  console.log(i)
  i++
}
Copy the code

Replace the new Object directly

  • Use literals instead of constructors
// example1
const a = new Array(3) // Involves a function call, which consumes a little more
a[0] = 1
a[1] = 2
a[2] = 3 
// example2- fastest
const a = [1.2.3] 
Copy the code

Document fragmentation optimization node added

  • Reduce reflux redraw
// example1
for (var i = 0; i< 10; i++) {
  var op = document.createElement('p')
  op.innerHTML = i
  document.body.appendChild(op)
}
// example2- fastest
const frgEle = document.createDocumentFragment()
for (var i = 0; i< 10; i++) {
  var op = document.createElement('p')
  op.innerHTML = i
  frgEle.appendChild(op)
}
document.body.appendChild(frgEle)
Copy the code

Clone optimized node operation

  • Cloning a node is faster than creating one
// example1
for (var i = 0; i< 3; i++) {
    var op = document.createElement('p')
    op.innerHTML = i
    document.body.appendChild(op)
  }
// example2- fastest
const oldEle = document.getElementById('box1')
for (var i = 0; i< 10; i++) {
  var op = oldEle.cloneNode(false)
  op.innerHTML = i
  document.body.appendChild(op)
} 
Copy the code