Introduction to JavaScript Profiler

Mehvish Ashiq Feb 15, 2024
  1. What is JavaScript Profiler and Why Is it Used
  2. Use Chrome DevTools for JavaScript Profiler
  3. Use the console.profile() Method of Node.js for JavaScript Profiling
Introduction to JavaScript Profiler

This tutorial introduces JavaScript Profiler that highlights its importance and usage. We’ll use various example codes to learn more clearly.

What is JavaScript Profiler and Why Is it Used

Using JavaScript Profiler, we can observe which processes, methods, and functions consume maximum time. It is a tool that we can use to analyze & optimize the code.

Although there are different JavaScript Profilers that we can use, we’ll be focusing on Node.js console.profile() and JavaScript Profiler on Chrome DevTools for this article.

We can open Chrome DevTools by pressing F12 or Ctrl+Shift+i, or by going to Right Click -> Inspect -> JavaScript Profiler.

Use Chrome DevTools for JavaScript Profiler

Using the following startup code, let’s start with the Chrome DevTools JavaScript Profiler easiest way.

HTML Code:

<!DOCTYPE html>
<html>
 	<head>
 		<title>JavaScript Profiling</title>
 		<script src="./script.js"></script>
 	</head>
 	<body>
 		<button id="btnUpdateCount">Click</button><span id="count"></span>
 	</body>
</html>

JavaScript Code (script.js):

function printMessage(message) {
  console.log(message);
  console.warn(message);
  console.error(message);
}

var msg = 'Welcome to JS Profiling';
printMessage(msg);

var i = 0;
window.onload = function() {
  document.getElementById('btnUpdateCount').onclick = function() {
    document.getElementById('count').innerHTML = i++;
  }
}

Output:

introduction to javascript profiler - chrome devtools output

Use the console.profile() Method of Node.js for JavaScript Profiling

JavaScript Code:

function JSProfile(callback) {
  try {
    for (var i = 1; i < 4; i++) {
      console.log('Working on project:', i);
      callback();
    }
  } catch {
    console.error('There is an error');
  }
}

console.profile('JSProfile()');
JSProfile(function alfa() {
  console.profileEnd();
});

Output on Console:

Working on project: 1
Working on project: 2
Working on project: 3

Output in Inspector:

introduction to javascript profiler - nodejs profile method output

The built-in method console.profile() only prints when the program starts the JavaScript CPU Profile in the inspector. Then, it is added to the inspector’s Profile panel.

Remember, it only works in the inspector.

Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook