4 ms·
JavaScript's For-Of Loops Are Fast
- phillipseamore 10mo agoBut still just 85% of a conventional cached loop (34 vs 40 ops/s per the last test).
- senfiaj 10mo agoThe author here, I ran another test here https://jsben.ch/QCXCY https://jsben.ch/QCXCY . https://jsbenchmark.com/ https://jsbenchmark.com/ seems to have issues with longer running code. 1500 repeats, for me for-of is now on par with classic for. As I said, for-of loops are not optimized as easily and reliably because v8 has to prove certain things to be able to do so. For-of's default is iterator protocol, and its more sensitive to deoptimization.
- phillipseamore 10mo agoGot similar results but then tested on an older win10 i5 system (8+ years old?) chrome 145 and get variable results but classic is always about twice foreach or forof and foreach often performs 2x better than forof. I fear this might be more connected to CPUs than anything.
- senfiaj 10mo agoWeird. If V8 produces different optimized codes for different loops, this might be true on some CPUs. But when I get 100% convergence when increasing the repeats, this becomes a bit suspicious. Also, it might be some timing difference related to initial warmup or some adjustments in V8 for specific CPUs (including some power saving). I also ran on Pixel 3a , both classic and for-of were 100%, foreach was ~9% (on Windows 11 and AMD Ryzen 5000U was the same, except foreach was 62.96%). I created another benchmark https://jsben.ch/sdaEM https://jsben.ch/sdaEM . The difference is that doSomethingWithValue now assigns the passed value to some variable. I think the optimizer could still notice that the function was dummy and do weird things, but not sure 100%. So I store in a variable to prevent this. Now the tests run slower, but still both classic and for-of tend to be 100%. forEach is sometimes slower, sometimes on par with the other 2 (on both AMD Ryzen 5000U Laptop and Pixel 3a). Could you please run this test on your mentioned machine? Also could you gradually increase the number of repeats in each test case and see if there is some convergence? Also make sure the tab and the browser window are active during the benchmark. Otherwise the browser / OS might give less priority to the task. And BTW, can you also test on Chrome 143 and even Chrome 144 (it will be released tomorrow)?
- jauntywundrkind 10mo ago100% / 92% / ~32% (forget exactly on this one) for for-of, classic, forEach for me, on a Ryzen 5700 AMD desktop. Other things running, not a fantastic test, but I did turn the cooling system up ahead of running. This defied my expectations & I had to try & see! Side note, I am fantastically glad to see at least some kind of online javascript benchmarking site is alive again. https://jsperf.com https://jsperf.com was so good to us for so many years. Obviously there's flaws but the way that it not just was a benchmark site but also would record folks results & aggregate them was incredibly incredibly incredibly fantastically sweet.
- throw_m239339 10mo agoOP forgot to mention that speed is relative ;)
- Aldipower 10mo agoThe old and famous jsperf.com is available under .app again. Here is a for/while comparison f.ex.: https://jsperf.app/doyeka/5 https://jsperf.app/doyeka/5
- fainpul 10mo agoI tested Firefox, Safari and Brave on macOS. Results are totally different for each. "for loop, positive" seems to be the only safe bet. Safari was very slow on everything, Brave and Firefox were slow on `for … of`. I'm surprised by the huge variance. Can these results be trusted?
- ygra 10mo agoThe way the array is constructed at least leads to holey arrays in V8. Perhaps similar in other implementations. The performance characteristics between different array types may vary significantly as well. Still, the traditional for loop, counting upwards seems to be fastest for me across Chrome and Firefox on Linux. For-of is slowest by a wide margin.
- nitwit005 10mo agoThere is always going to be a big gap between a browser that had a particular optimization, and one where it is absent. But, browsers are an odd case where optimizations often prove not to be worth it on real world websites. The cost to optimize can easily exceed the savings.
- xlii 10mo agoOn Safari are results were within 3% of each other. On Brave "for loop, negative" was 84% faster than "for of". This small sample (2 browsers on macOS) align with my expectations of "Good luck optimizing JavaScript that has dozen of different implementations".
- behnamoh 10mo agoJesuS, so many different ways for looping in a language is insane. And Racket takes it to the next level...
- pjmlp 10mo agoA better point would be V8 execution of JavaScript's for-of loops is fast. We should not make assertions based on a language name, when there are so many implementations to chose from, https://zoo.js.org/ https://zoo.js.org/
- Aldipower 10mo agoThanks, that's a good picture and history of JS engines.
- mcny 10mo agoSpider monkey being under 24k while v8 and JavaScript Core kiss 60k is alarming. Why are we so far behind?
- pjmlp 10mo agoBasically lack of human resources to make it great, note that Firefox is already around 3% market share, and Mozilla keeps having other priorities.
- wiseowise 10mo agoNo wonder my Firefox feels sluggish compared to Chrome on M3. Sigh.
- Hendrikto 10mo agoMozilla has their priorities ass backwards and does anything except what prople actually want: developing Firefox.
- tracker1 10mo ago+1 on this... the spend outside of development is kind of fascinating as a while IMO. That they let Thunderbird languish for so long, they pretty much nuked XULRunner, and a bunch of pretty cool tech along the way.
- nofriend 10mo agoFirefox is optimized against speedometer and similar "real world" benchmarks. This is a list of highly artificial benchmarks. Mozilla could attempt to optimize it for these benchmarks, but it wouldn't do much to make the web browsing experience better.
- panstromek 10mo agoThere's so many ways this benchmark can go wrong that there's pretty much no way I can trust this conclusion. > All the loops call a dummy function DATA.doSomethingWithValue() for each array element to make sure V8 doesn't optimize out something too much. This is probably the most worrying comment - what is "too much?" How are you sure it doesn't change between different implementations? Are you sure v8 doesn't do anything you don't expect? If you don't look into what's actually happening in the engine, you have no idea at this point. Either you do the real work and measure that, or do the fake work but verify that the engine does what you think it does.
- crabmusket 10mo agoThere are a lot of "probably"s in the article. I was also suspicious that the author didn't say they did any pre measurement runs of the code to ensure that it was warmed up first. Nor did they e.g. use V8 arguments with Node (like --trace-opt) to check what was actually happening.
- lerp-io 10mo agou can compile to v8 turbofan final bytecode and use ai to analyze and compare the instructions.
- ssttoo 10mo ago> to make sure V8 doesn't optimize out something too much A bit more explanation of “something” and ”too much“ would have been educational
- egeozcan 10mo agoFor-of loops are fast enough, most of the time. You probably still don't want to risk it in a tight loop. Relying on those optimizations may not be the most reliable choice when you think about all the different JS engines, platforms, system load, operating systems...
- latexr 10mo ago> This site uses cookies. By continuing to use this website, you agree to their use. Careful, you are in violation of the GDPR. You can’t simply say “I’m going to set non-essential advertising cookies, deal with it or get out” (I checked your policy to confirm you are using non-essential cookies), you can’t set any cookies until the user agrees, and have to provide a way to reject them that is at least as simple as the way to accept.
- Alupis 10mo agoIt's a personal blog of someone living in Armenia. What's the EU going to do? Despite what many EU citizens may think, EU laws don't apply to the world.
- latexr 10mo agoIf they didn’t care about those laws, they wouldn’t need the notice. Since they do, they do. Why are you even mad? This doesn’t affect you, it is not directed at you, and is trying to be a helpful clarification to the author. If they care about compliance, presumably they care about doing it right. > Despite what many EU citizens may think, EU laws don't apply to the world. I’m a EU citizen living in the EU and have never encountered or heard of anyone with that belief.
- ndr 10mo ago> I’m a EU citizen living in the EU and have never encountered or heard of anyone with that belief. See 4chan vs OSA. EU is similarly trying to legislate for the world, and it will work until someone calls on their bluff. I'm in EU most of the time and like most benefits of GDPR (right to access and delete? Great!) But sometimes they overplay their hand.
- latexr 10mo ago> See 4chan vs OSA. OSA is a UK legislation. The UK is not in the EU. > EU is similarly trying to legislate for the world, and it will work until someone calls on their bluff. That’s an opinion. The Brussels Effect is real, but that’s not the same as “many EU citizens think EU laws apply to the world”.
- g947o 10mo agoFunny enough, for-of is not allowed in Airbnb eslint config, and you are expected to use forEach instead: https://github.com/airbnb/javascript/issues/1122 https://github.com/airbnb/javascript/issues/1122 https://github.com/airbnb/javascript/issues/1271 https://github.com/airbnb/javascript/issues/1271 Because the style guide thinks "forEach is cleaner than for-of". (No I did not make that up.) https://github.com/airbnb/javascript?tab=readme-ov-file#iterators--nope https://github.com/airbnb/javascript?tab=readme-ov-file#iter...
- wiseowise 10mo agoNo way this is not a satire. https://github.com/airbnb/javascript/issues/1122#issuecomment-259876436 https://github.com/airbnb/javascript/issues/1122#issuecommen... https://github.com/airbnb/javascript/issues/1122#issuecomment-259884000 https://github.com/airbnb/javascript/issues/1122#issuecommen...
- g947o 10mo agoI know. Which is why I completely got rid of airbnb rules in my personal projects or projects that I control. I wasted so much time fighting those stupid rules instead of actually writing code.
- vorticalbox 10mo agoi have pretty strict rules for the code bases at work and one is to use for..of
- tentacleuno 10mo agoThey don't seem to like generators either, which is even stranger. Why block the usage of features which might be useful in some cases?
- deleted 10mo ago[deleted]
- mattacular 10mo ago
- phplovesong 10mo agoItems you loop are 99% under 1000 items.
- tracker1 10mo agoI almost always try to cap my API results to 10001 items, so it's known if there's "more", depending on the interface(s) used. And when there are more, there's usually other pattern problems with the UX that I'm just kicking a can down the road on at that point. Even then, far less than an amount one needs to be concerned of, for "performance"
- injidup 10mo agoWhat's with the "accept" only button for cookies on this website. If you drill down through the cookies link it explains in over verbose detail how you can disable tracking for individual cookies and each cookie has a unique disabling strategy even down to a suggestion to install some plugin. This is certainly not in line with EU rules on cookie banners.
- throawayonthe 10mo agolol and the first time you click the theme change button it goes through a series of tracking redirects ending in some crypto app (at least on mobile)
- exyi 10mo agoOnly until you work with a type array (Int32Array, Float64Array, etc), then it becomes 10x slower: https://jsperf.app/doyeka/11 https://jsperf.app/doyeka/11
- trgn 10mo agoAnd it's still worse, and has to rely on contrived setups to almost reach parity. People will insist on using a new language construct, even if it's objectively worse than the standard. What's so hard about a conventional for (let i ...) loop? At least for of is better than forEach (ill never forgive crockford for goading people into this functional-lite code with horrible runtime footprint), but these things are fetishes.
- nobleach 10mo ago>new language construct This was added to the language 10 years ago. So while it's "newer" than a plain old for-loop, it's definitely not "new". It was designed to work with Symbol.iterator. This is the mechanism whereby one can iterate anything that implements the Symbol.iterator interface. As far as why folks won't just do simple for-loops, it's the same reasining every language tends to implement a "foreach", because there are annoying off-by-one errors lurking in the < vs <=. Of course one could argue that developers should be smart enough to handle this. But that's an argument even older than for-loops.
- trgn 10mo ago> here are annoying off-by-one errors These barely if ever happen for simple iterations, it's an idee fixe. Off-by-one sneak in when trying to do something special, and then a for-on loop is useless anyway. > Symbol.iterator interface I get it, but it's unnecessary abstraction to overgeneralize a vanilla array to an iterable. anyway, for..of is not an issue, it's alright. I think if there's one main point i'm trying to make, is that devs will write objectively worse code base on gut wants (in this case, obsession to use higer level abstractions to iterate over an array).
- robin_reala 10mo agoIt’s like the “…in mice” trope for medical study headlines, but with “…in V8” instead.
- tracker1 10mo agoIs anyone really dealing with this much data in-memory in JS? I'm just curious, as I've been at this for about 30 years now, and the only times I've dealt with this much data, it's mostly been in streaming/etl type work, where you aren't using it all in-memory at once. Personally, I like the for-of syntax as well as for-await-of... I kind of wish there was a promise-based version of forEach, as sometimes this syntax sits better, though I'm more inclined to use map, find, etc. over forEach. If I'm not using the indexer value, then there's not much point in using arr[i] over the for-of. Also, in practice, I've RARELY found the need to optimize how JS is used outside refactoring a recursive algorithm when there's risk of a stack overflow.
- simonw 10mo agoIncreasingly yes. A modern browser on a good laptop can crunch on GBs of data in a browser tab at once. This makes all sorts of data analysis and visualization tasks feasible in a client-side web app where previously you would have needed a detected database server somewhere. Take a look at the https://kepler.gl/ https://kepler.gl/ demos to see quite how sophisticated this stuff can get now - millions of geospatial data points rendered entirely clientside via WebGL.
- tracker1 10mo agoThanks... the vast majority of my own experience has been a combination of line of business, banking, security and govt applications outside of scientific heavy circles, so was a genuine question, despite the downvotes.