Better, Faster, Code

Hi,
In the never-ending quest to make our code faster, more efficient, and simpler, I have a number of questions to ask you all (the experienced and sage veterans) what JavaScript code structures (objects v. arrays for instance) are more efficient than others. I would like some general tips and, if possible, articles that explain the subject more in depth.
Thank you in advance,

I don’t know why but functions that return objects in Javascript (iterators and generators) are way more performant than closures.
There are no zero cost abstractions in JS.

If you have a nested for loop or recursive function consider replacing it with a generator and *yield another generator e.g.

const  nestedFor = function*(obj){
for(let i of obj){
yield i + 1;
}
const myGen = function*(obj){
for let(i of obj){
if(typeof(i) == 'object') yield* nestedFor(i);
else yield i + 1;
}}

Functional type programming although great for code re-use isn’t that great for performance. function => function => function => function =>

On that note async await is more performant than Promise.then(), probably because I think under the hood it’s similar to generators (there were async await hack libraries using generators(ES6) before official async await in ES7) and it’s not returning a new Promise object every .then().

Also you have to constantly test performance and re write code to do the minimal amount of work whilst getting the job done.

I just re wrote a streaming module to async iterators and a few async generators and reduced the performance time from 30ms to 2.5ms.

1 Like

Thank you for the suggestions!
I have not looked at JavaScript past ECMA6, so this is the first time I have heard the term “generator functions” or “async.” I also have been looking around and have found that there are a lot more features to JavaScript that I don’t know, so I will be learning them. Thank you again.

2 Likes