Introduction to JavaScript Profiler
- What is JavaScript Profiler and Why Is it Used
- Use Chrome DevTools for JavaScript Profiler
-
Use the
console.profile()
Method of Node.js for JavaScript Profiling
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:
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:
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.