Sometimes we need to know if our code is fast enough for a production environment, for example let’s take a simple javascript function like that:
It’s a very simple function, isn’t it? :)
But you in an inspired day, decide to create a way to abstract the code above to something like a template method, thus you could use that at other functions. Let’s see our new function:
Now we have our cool template function, but let’s wonder ourselves if we could have some performance issues adding that new function. What do you think about it?
Yeah, probably you’re thinking about a way to measure our new function against the first one, and that’s exactly what we’re going to do.
To do that, we can use these two functions console.time() and console.timeEnd() to measure the time taken by a function execution. The function console.time() takes a timer name, and console.timeEnd() must take the same timer name, then it’ll report on the execution time since the timer started. Let’s use them to measure our two functions:
And the output is:
Wow, the second function is about 7 times slower than the first one, and it would probably be a problem in a real application.