Performance issues? Find your bottleneck with console.time()
My, since a little while beautiful, app called What?! was a little slow when opening files. A lot slower since the version before the big redesign. When you changed a lot it is hard to find a starting point. What you can do about this? You already read the title so you know the answer. Tldr; just try it.
The `console.log()` function is something most JS developers know, you can output anything to the console (for Node as well as the browser). I think a lot of developers do not know about `console.time()` though. Probably something you will use a lot less, but can be very useful.
Okay, so let’s find that slow little bastard of a function. What you need to know:
- console.time(‘example’) will start a timer, where you also give it a name. You can start multiple timers (simultaneously), if choose different names. It will not console anything though.
- console.timeLog(‘example’) gives you the amount of elapsed milliseconds in the console. Make sure to start a timer first and same name. Tip: you can call it multiple times to see where the biggest time jumps in your process are made.
- console.timeEnd(‘example’) will stop the timer and console log the amount of elapsed milliseconds.
Put the `console.time()` at the start of your slow process and drop a few timeLog’s through the process. In places where different things are done, or maybe expect performance issues. Do not forget to stop the timer at the end.
Do you have simultaneous tasks or a lot of steps? You can start multiple timers, measure the overal process and start separate timers for certain tasks/steps to get a better picture. Do whatever you need to see what piece of your code is taking too much time, just start and try.
Hopefully you did find the son of a gun. Now you may have some ideas to implement it differently, maybe >1 options. Let’s implement them! Now you can try out things, make a duplicate function with a different implementation. Keep `console.time()` in your code to measure the before/after.
When you do have multiple solutions, check all of them out (or some of them) and see which one is the fastest. You already have the test bench set up, now is the time!
Next up: pick your solution, remove your console functions because you don’t want them in production code, go to the store, buy confetti and celebrate! Your application got faster, congratulations :)
Of course there are a lot more options for debugging performance, and a lot more tools to work with. I like this one because it is easy and accessible for everybody who is in need.
It helped me to get my app What?! to be a lot faster. Especially on the larger translation files. Be careful with deep cloning large objects, lesson learned.