JS/TS performance snippets
Snippets and performance hints.
Prefer maps to objects for dynamic data
Objects aren’t ideal for manipulation, especially in Typescript. If you add a key, the typings get thrown of. Prefer a JS Map.
Checking if items is in list
new Set(arr).has(item) is actually much faster than Array.includes() for checking the existence of primitives in a set. Prefer that.
If you need a function for lookup, use Array.some()
Delete single item from list
Just as above. Array.from(new Set(arr).delete(key)) is faster than removing it with filter. Also works only on primitives.
Prefer for…of for Array.forEach
You get more loop control like continue or break and it works on all iterables not just arrays. It supposedly also leads to better patterns, where instead of using multiple Array.filter you can just continue in the for-loop and skip a full loop.
Learned from Biome linter rules
Try to avoid …spreads as much as possible
Using a reduce pattern like
arr.reduce((acc, item) => {
return {
...acc,
[item.key]: item.value,
};
}, {});
Increases the time complexity to O(n²) since everything in acc will be iterated over again and again.
A better pattern would be this:
arr.reduce((acc, item) => {
acc[item.key] = item.value;
return acc;
}, {});
Other patterns that might be useful are Array.push or similar ways to add to an existing array.
In the end, you also prevent creating more objects and arrays like this, decreasing the memory load.
Learned from Biome linter rules