I recently came across an informative article discussing V8 engine and javascript optimization.
How JavaScript works: inside the V8 engine + 5 tips on how to write optimized code
The article highlights some key recommendations:
a. V8 engine utilizes hidden classes and a caching mechanism for these hidden classes and properties. It is advised to avoid dynamically adding object properties or changing property types. Instead, use object constructor functions.
b. The V8 engine optimizes frequently used functions more effectively. To benefit from this, it is recommended to avoid generating many different similar form functions that are executed only once. Opt for writing code that repeats the execution of the same function instead.
Now, I have three questions in mind:
i. Can recommendations 'a' and 'b' be applied to other browsers' javascript engines, such as Firefox's SpiderMonkey?
ii. With regards to recommendation 'a', is using TypeScript more advantageous for V8 engine optimization? (With TypeScript, you can produce JavaScript code with fewer dynamically changing objects and properties)
iii. Modern JavaScript code often includes a lot of inline and anonymous functions with similar forms, like the example code provided below. According to recommendation 'b', would it be more beneficial to use a single predefined function instead? (Note: This example code is simplified to demonstrate the repetition of similar form functions)
prm.then((res) => {
console.log(res);
}).then((res2) => {
console.log(res2);
}).catch((err) => {
console.log(err);
});