articles

Home / DeveloperSection / Articles / Performance Optimization in JavaScript

Performance Optimization in JavaScript

Performance Optimization in JavaScript

Ashutosh Kumar Verma 167 25-Jun-2024

JavaScript Performance Optimization 

Performance optimization in JavaScript includes many techniques and best practices aimed at improving the performance and speed of your code. Here are the main areas and ways to optimize JavaScript performance.

 

Reduce DOM Access

Minimize the number of DOM access- DOM access is slow. Store DOM elements in variables as you move more.

// Inefficient
document.getElementById('myElement').style.color = 'red';
document.getElementById('myElement').style.backgroundColor = 'blue';
// Efficient
const myElement = document.getElementById('myElement');
myElement.style.color = 'red';
myElement.style.backgroundColor = 'blue';

Batch DOM updates- Avoid forced reflow by batching DOM manipulations together.

const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {
 const div = document.createElement('div');
 div.textContent = `Item ${i}`;
 fragment.appendChild(div);
}
document.body.appendChild(fragment);

 

 

Optimize Loops

Use appropriate loop constructs- If performance is important, prefer simple loops like for and while over higher-level functions like forEach.

// More performant
for (let i = 0; i < array.length; i++) {
 // ...
}
// Less performant in some cases
array.forEach(item => {
 // ...
});

Minimize loop calculations- Calculate values ​​that don't change outside the loop.

// Inefficient
for (let i = 0; i < array.length; i++) {
 const len = array.length;
 // ...
}
// Efficient
const len = array.length;
for (let i = 0; i < len; i++) {
 // ...
}

 

Efficient Event Handling

Debounce and Throttle Events- Use debouncing and throttling to limit the rate at which jobs execute, especially for scroll, size, and input events.

function debounce(func, wait) {
 let timeout;
 return function(...args) {
   const later = () => {
     clearTimeout(timeout);
     func.apply(this, args);
   };
   clearTimeout(timeout);
   timeout = setTimeout(later, wait);
 };
}
window.addEventListener('resize', debounce(() => {
 console.log('Resized!');
}, 200));

 

Asynchronous JavaScript

Use async/await and Promises- Write non-blocking code using Promises and async/await.

async function fetchData() {
 try {
   const response = await fetch('https://api.example.com/data');
   const data = await response.json();
   console.log(data);
 } catch (error) {
   console.error('Error fetching data:', error);
 }
}

 

Optimize memory usage

Avoiding memory leaks- Closures, focus on event listeners and global variables that can cause memory leaks.

function attachEvent() {
 const element = document.getElementById('myElement');
 element.addEventListener('click', function handleClick() {
   // event handling logic
   // Ensure to remove the event listener if no longer needed
   element.removeEventListener('click', handleClick);
 });
}

 

Use Efficient Data Structures

Choose the right data structure- Use an array, set, map, or object as appropriate for the task.

// Efficient for frequent updates and lookups
const map = new Map();
map.set('key', 'value');
// Efficient for simple lists
const array = [1, 2, 3];

 

Minify and Compress JavaScript

Minify JavaScript files- Use tools like UglifyJS or Terser to shrink JavaScript files, reduce file size and improve load time.
Enable Gzip or Brotli compression- Configure your server to encrypt JavaScript files to further reduce load times.

 

Lazy full load handling

Lazy load images and other features- Only load content when you need it, especially images.

const img = new Image();
img.src = 'path/to/image.jpg';
img.loading = 'lazy';
document.body.appendChild(img);

 

Avoid unnecessary Computations

Memoization- Cache the results of expensive function calls and reuse the cache when the same input is returned.

function memoize(fn) {
 const cache = new Map();
 return function (...args) {
   const key = JSON.stringify(args);
   if (cache.has(key)) {
     return cache.get(key);
   }
   const result = fn(...args);
   cache.set(key, result);
   return result;
 };
}
const expensiveFunction = memoize((x, y) => x + y);

 

Using these techniques, you can dramatically increase the performance of your JavaScript code, making your web applications more efficient and effective.

 

Also, Read: Explain the JSON in JavaScript


Updated 25-Jun-2024
Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By