Hello there 😉
I'm honored to welcome you - nice reader of this post - in the first part of the first article series on this blog called "Let's talk JS" in which I'll discuss some general programming-language specific features of my favorite - JS. Without further ado - let's begin!
A bit of theory 📚
I want more...
And more you'll get my friend with JS engines ( especially V8 ) getting faster and more feature-full. The demand for performant JS code is now bigger than ever. Sadly, JS can get just as good as it's possible, so ( for an interpreted language ) not that much more. That's why new web-development tools like WebAssembly (WASM) are becoming more and more popular. You can read more about WASM in my other article and around the internet. Anyway, for now constant, positive growth in the performance of JS can be observed with a smile on the face of every JS programmer.
So, where are we now?
Of course, besides the implementation, important for performance is the quality of the written code. So, how to write code that can be well-optimized by V8's JIT compiler ( yes, only well written and a repetitive code is JIT-compiled for better performance ) Keep in mind that I'm not talking about such aspects of the language as web APIs and DOM operations - only bare code execution.
Let's KISS it!
- Minify / optimize your files with tools like Uglify.js ( obviously );
- Animate using
- Preallocate & initialize arrays with
- Reuse instances & object whenever possible without any costly performance changes;
- Avoid binding functions with
Function.call()or ( in ES6 ) arrow functions;
undefinedrather than using
- Avoid type convertion.
- In if/else and switch keep most common condition first;
- Avoid accessing variables outside of the scope whenever possible;
whileloops whenever possible;
- Use ASM.js if you want
- Use WebWorkers for computation-heavy operations;
- Do not over optimize!
- Just KISS your code 😘
So, there you have it - list of the most general optimization tips for JS. Even if some are obvious, some can be not as much and some can be just forgotten.
Thanks for reading till the end of this post. If you liked it - consider sharing this performant article ⚡ with others on Twitter or sharing your thoughts below. Have a nice day/night!