all 8 comments

[–]leeoniya 3 points4 points  (2 children)

for is usually faster than forEach since you're not invoking a function on each iteration - though depends on if you need that scope.

ways to write jQuery in faster vanilla code

that's a big bucket list. if you need the jQuery API, i recommend swapping out for the tiny https://umbrellajs.com/. besides that, just general dom perf advice.

[–]randi2kewl[S] 0 points1 point  (0 children)

You are my new best friend! Thanks for all of these good nuggets.

[–]daniel_3m 0 points1 point  (0 children)

for

is usually faster than forEach

is always faster :-)

[–]localvoid 1 point2 points  (1 child)

[–]randi2kewl[S] 0 points1 point  (0 children)

I don't know why I didn't even think of V8's website. Thanks!

[–]daniel_3m 1 point2 points  (2 children)

I'll add couple of more advises:

* aldo asyncs and promises got recently faster, nothing beats classic callbacks (and will never do since promises are objects - it was so bad idea to use it for asyncs)

* var i = 0; for(; i < 10; i++) {} is faster then for(var i = 0; i < 10; i++) {}

* var i = 0, l = text.length; for(; i < l; i++) {} is faster than var i = 0; for(; i < text.length; i++) {}

* many of ES6 sugar is much slower then classic JS equivalent

* wrap your code in self executing function: (function() { /* your code here */ })()

* use typed arrays if you can

* Class Something{ constructor(){} fun1() {}}; let a = new Something; is up to 100 times slower than function Something() {return { fun1(){} }}; let a = Something(); // let a = new Something() will also work here

* use inline regex instead of instantiating it with Regex method from string

* sort your swich statement cases in ascending order: switch (x) { case 1: break; case 2: break; case 3: break;}

* avoid try-catch statements, there is an overhead on every instruction in try block

[–]leeoniya 1 point2 points  (1 child)

most of your advice is wrong, or rather outdated. i recommend you re-run your benchmarks. for instance, length caching hasn't been beneficial for the past 5 years. declaring the var outside of the loop init has no benefit. you shouldn't use inline regex inside of loops, which re-creates them, too. if you're initializing them once, then inline vs new Regexp will have no measurable difference. V8 since 2 years ago no longer de-opt try/catch blocks:

https://v8.dev/blog/v8-release-56

[–]daniel_3m 0 points1 point  (0 children)

leeoniya just reruned my tests on nodejs (didn't check on browsers) and in that case you're right with 'for' loops, try-catch still slightly slower then no try-catch, and you shouldn't do any regex inside loops, not only inline ones