console.time() & console.timeEnd()

A quick tip on how to use the console.time() and console.timeEnd() methods from the Google Chrome Devtools API.

console.time() & console.timeEnd()

Here's a ⚡️quick tip on how to benchmark your code from within the Google Chrome Console using both console.time() and console.timeEnd().

Setting up console.time()

As with almost all of the Chrome Console APIs, console.time() and console.timeEnd() are both prety straightforward and extremely useful.

If you've ever wondered to yourself if one particular piece of code is executed faster than another, here's a way to get a good idea!

Syntax

console.time([label]); // add an optional label to your timer

console.timeEnd(); // close out the timer

As you can see, the syntax is pretty straight forward. You are able to add labels to the console.time(). This will help to keep your logs more organized in the event that you wanted to run multiple timers within your code.

Example

Let's create a simple array that we will iterate over using both a standard for-loop as well as the Array.forEach() method. From there, we will use console.time() to give us some benchmarks of the performance between the two.

const arr = [1, 2, 3, 4, 5, 6, 7, 8 , 9 , 0];

function countWithForLoop(arr){
    console.time(); // start timer
	var count = 0;
    for (var i in arr) {
		count++;
	}
	console.timeEnd(); // end timer
	return count;
}

function countWithForEach(arr){
	console.time(); // start timer
	count = 0
	arr.forEach(item => {
		count++;
	})
	console.timeEnd(); // end timer
	return count;
}

countWithForLoop(arr); // returns a faster time

countWithForEach(arr); // returns a slower time

Try this the code snippet in your browser console.

The Output

After running a fair amount of trials, it's fair to say that countWithForLoop() will iterate through arr faster than countWithForEach().

codesnippet-console-time

It's worth noting that this isn't the most scientific way to benchmark the performance of two pieces of code, but it will certainly give you a pretty solid idea in a matter of seconds.

Stay Tuned 📺

I hope you found this ⚡️quick tip useful! There's a ton of other awesome methods in the Google Chrome Devtools API so stay tuned for more!

If you have any questions or improvements, or if you'd like to see additional examples, feel free to reach out to me anytime at [email protected]. If you're enjoying my posts, please subscribe below! 👇

Help us improve our content