How to Optimize JavaScript Code for Performance

1. Minification and Compression

Description:
Minification removes unnecessary characters from the source code (like spaces, comments, and new lines), while compression reduces the overall file size. These techniques speed up file download and parsing time. Tools like UglifyJS, Terser, or online compressors are commonly used.

Example:

  • Original Code:

Javascript code

function add(a, b) {

  return a + b;

}

  • Minified Code:

Javascript code

function add(a,b){return a+b;}

2. Code Splitting

Description:
Code splitting involves breaking your code into smaller, more manageable pieces (chunks) that can be loaded on demand. This improves initial load time and optimizes resource usage.

Example:

  • Original Code:

Javascript code

// main.js

function add(a, b) {

  return a + b;

}

 

function multiply(a, b) {

  return a * b;

}

  • Code-Split Code:

Javascript code

// main.js

function add(a, b) {

  return a + b;

}

 

// math.js

function multiply(a, b) {

  return a * b;

}

3. Cache Frequently-Used Data

Description:
Caching stores frequently-accessed data locally to reduce redundant network requests. It enhances performance, especially for repetitive tasks or data that doesn’t change often.

Example:

  • Original Code:

Javascript code

function getUserData() {

  fetch(‘/api/user’)

    .then(response => response.json())

    .then(data => console.log(data));

}

  • Cached Code:

Javascript code

const cache = {};

 

function getUserData() {

  if (cache.userData) {

    console.log(cache.userData);

  } else {

    fetch(‘/api/user’)

      .then(response => response.json())

      .then(data => {

        cache.userData = data;

        console.log(data);

      });

  }

}

4. Optimize Loops

Description:
Reducing unnecessary iterations and improving loop logic minimizes computational overhead. This is particularly beneficial when dealing with large datasets.

Example:

  • Original Code:

Javascript code

for (let i = 0; i < 1000000; i++) {

  console.log(i);

}

  • Optimized Code:

Javascript code

const arr = Array.from({ length: 1000000 }, (_, i) => i);

console.log(arr);

5. Avoid DOM Manipulation

Description:
Frequent DOM manipulations cause excessive reflows and repaints, slowing down the application. Using techniques like batching changes into a DocumentFragment minimizes these performance hits.

Example:

  • Original Code:

Javascript code

for (let i = 0; i < 100; i++) {

  const div = document.createElement(‘div’);

  div.textContent = i;

  document.body.appendChild(div);

}

  • Optimized Code:

Javascript code

const fragment = document.createDocumentFragment();

for (let i = 0; i < 100; i++) {

  const div = document.createElement(‘div’);

  div.textContent = i;

  fragment.appendChild(div);

}

document.body.appendChild(fragment);

6. Use Efficient Data Structures

Description:
Choosing appropriate data structures (like Set for unique values or Map for key-value pairs) can significantly reduce time complexity and improve performance for large operations.

Example:

  • Original Code:

Javascript code

const arr = [];

for (let i = 0; i < 1000000; i++) {

  arr.push(i);

}

  • Optimized Code:

Javascript code

const set = new Set();

for (let i = 0; i < 1000000; i++) {

  set.add(i);

}

7. Avoid Global Variables

Description:
Global variables increase the risk of naming conflicts and can lead to unintended side effects. Keeping variables local ensures better performance and code maintainability.

Example:

  • Original Code:

Javascript code

let x = 10;

function add(a, b) {

  return a + b + x;

}

  • Optimized Code:

Javascript code

function add(a, b, x) {

  return a + b + x;

}

8. Optimize Event Listeners

Description:
Reducing the number of event listeners improves performance by avoiding redundant bindings. Delegating events to a common parent element is an efficient way to manage multiple listeners.

Example:

  • Original Code:

Javascript code

document.querySelectorAll(‘button’).forEach(button => {

  button.addEventListener(‘click’, () => {

    console.log(‘Button clicked!’);

  });

});

  • Optimized Code:

Javascript code

document.addEventListener(‘click’, event => {

  if (event.target.tagName === ‘BUTTON’) {

    console.log(‘Button clicked!’);

  }

});

9. Use Web Workers

Description:
Web Workers allow computationally intensive tasks to run on separate threads, preventing the main thread from blocking and improving responsiveness.

Example:

  • Original Code:

Javascript code

function calculatePi() {

  let pi = 0;

  for (let i = 0; i < 1000000; i++) {

    pi += 1 / (i * 2 + 1);

  }

  return pi;

}

  • Optimized Code:

Javascript code

// main.js

const worker = new Worker(‘worker.js’);

worker.postMessage(‘calculatePi’);

worker.onmessage = event => {

  console.log(event.data);

};

  • worker.js:

javascript code

self.onmessage = () => {

  let pi = 0;

  for (let i = 0; i < 1000000; i++) {

    pi += 1 / (i * 2 + 1);

  }

  self.postMessage(pi);

};

Leave a Comment