JavaScript, at its core, was architected with certain performance considerations in mind, but these considerations often get overshadowed by newer features designed for ease of use rather than efficiency.
It is especially important in JavaScript to find a balance between elegance and performance, as sometimes beauty can come at a cost.
This article explores 19 examples of TypeScript/JavaScript code patterns, comparing common, elegant approaches to their more optimized, but perhaps less attractive, counterparts.
The author used a structured performance testing framework to measure execution time and memory usage at varying scales, revealing when certain optimizations kick in and how different environments can influence results.
The article covers various topics such as string concatenation, array copying, looping over arrays, object property access, map usage, object cloning, and array filtering, among others.
Some surprising results were found, such as destructuring being faster than dot notation in a simple performance test. Also, the spread operator was faster than using Object.assign() for object cloning.
The article stresses the importance of testing performance trade-offs and not assuming that pretty code is always slower than ugly code.
The conclusion is that there is no clear winner between pretty but slow and ugly but fast. The choice depends on the specific use case and balancing the trade-offs between performance and readability.
Remember that the goal is to make more informed decisions when writing code, not to blindly assume that X is faster than Y. The only way to be 100% sure of your performance is to conduct your own tests.
If you're not running performance tests or measuring results, then you probably don't care about performance as much as you think.