DEV Community


Posted on


Console.time() and Console.timeEnd()

When people use web applications, they want them to deliver fast and efficient performance. As a result, speed has become one of the top metrics that people use to assess the quality of an application.

So, as a developer when we start working on a real-life application, then it's not only about achieving the desired result, it's also about how performant our code is?

Generally there are multiple ways a work can be done and it becomes important to take an informed decision while opting for a particular solution.

⭐ The console object's time() and timeEnd() methods can be used to analyse the performance of a piece of code.

First we call console.time() by providing a string argument, then the code that we want to test, then we call **console.timeEnd() **with the same string argument. That's all we need to do, it will now show us the time it took to run this piece of code in our browser console.


Let's swap two variables in two different ways, and let's find which one is more time-efficient.

1. Destructuring assignment

let a = 3;
let b = 4;
[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

O/P - Destructuring_assignment: 0.017333984375 ms

2. Temporary variable

let a = 3;
let b = 4;
let temp;
temp = a;
a = b;
b = temp;
Enter fullscreen mode Exit fullscreen mode

O/P - Temporary_variable: 0.008056640625 ms

We can see that by using these techniques, we can quickly obtain the elapsed time in milliseconds, which will aid us in identifying the bottleneck in our code and refactoring it.

⛔Note: In this post, I'm talking about the solution by only considering the time factor. There are other factors also that need to be considered while working on a project.

Top comments (0)

Advice For Junior Developers

Advice from a career of 15+ years for new and beginner developers just getting started on their journey.