As an engineer, especially when working on enterprise-grade applications, your coding is influenced by many factors. It is no longer about what function worked or your ability to achieve your desired result. It is rather about writing a performant code, thinking about time complexity vs space complexity, scaling, and ensuring that your application is as fast as possible.
In this tutorial, I'll be showing you how to make an informed decision using Javascript console Object methods console.time()
and console.timeEnd()
. Yeah, I know you're used to console.log()
.
To understand this, I'll be using a stopwatch to illustrate. Let's assume you wanted to start a race, you would start your stopwatch and when the race ends, you would stop your stopwatch. See console.time()
as starting your stopwatch and console.timeEnd()
as stopping your stopwatch. Easy right?
I want to merge two Objects with time complexity in mind. Remember, it is not about what works but what works in the shortest time.
EXAMPLE 1:
const object_1 = {
id: 3,
age: 4,
gender: 'male',
name: 'John'
}
const object_2 = {
car: "Honda",
colour: "black",
year: "2021"
}
//Start the timer
console.time('object_assign')
const merge_1 = Object.assign(object_1, object_2);
console.timeEnd('object_assign')
//end the timer
//Start the timer
console.time('rest_operator')
const merge_2 = {...object_1,...object_1}
console.timeEnd('rest_operator')
//end the timer
In the above code, I merged two objects using Object constructor method Object.assign()
and Javascript spread operator.
NB: console.time()
takes the parameter "label" and the label must be the same name when calling console.timeEnd()
to stop the timer and get the time output to the console. If the label name is not the same, it will throw Warning: No such label '{label name}' for console.timeEnd()
.
Time output on the console:
object_assign: 0.257ms
rest_operator: 0.032ms
From the console output, rest/spread operator is faster than Object.assign()
Again, this tutorial is focused on how to use console.time()
and console.timeEnd()
to make an informed decision and not why rest operators should be used over Object.assign()
.
EXAMPLE 2:
const arr = [1,3,4,5,3]
//Start timer
console.time("map")
arr.map(item => item)
console.timeEnd('map')
//End timer
//Start timer
console.time("forEach")
arr.forEach(element=>element)
console.timeEnd('forEach')
//End timer
RESPONSE:
map: 0.188ms
forEach: 0.035ms
console.time()
and console.timeEnd()
can also be used as a quick debugging tool to identify bottlenecks in our application.
Check MDN documentation for console.time() and console.timeEnd()
Top comments (1)
How you can get the console.time() into a variable and then print it in console.log ?