The fastest way to iterate a List in C# is NOT what you think

2022 ж. 14 Қыр.
153 865 Рет қаралды

Check out my courses: dometrain.com
Become a Patreon and get source code access: / nickchapsas
Hello everybody I'm Nick and in this video I will show you all the way you can iterate a List in C# and then show you what is by far the fastest and most memory efficient way. You might have guessed where this is going :)
Don't forget to comment, like and subscribe :)
Social Media:
Follow me on GitHub: bit.ly/ChapsasGitHub
Follow me on Twitter: bit.ly/ChapsasTwitter
Connect on LinkedIn: bit.ly/ChapsasLinkedIn
Keep coding merch: keepcoding.shop
#csharp #dotnet

Пікірлер
  • Nick should get a shirt with "I Stan the Span" printed on it

    @capsey_@capsey_ Жыл бұрын
    • Coming on a t-shirt near you twitter.com/nickchapsas/status/1523025560774987777

      @nickchapsas@nickchapsas Жыл бұрын
    • @@nickchapsas Coming on a t-shirt??? 😳😳

      @joshstather3543@joshstather3543 Жыл бұрын
    • I would buy that

      @foamtoaster9742@foamtoaster9742 Жыл бұрын
    • WriteLine'd on it*

      @Zatrit@Zatrit Жыл бұрын
  • I love the humor of using 80085 as your seed and I'm not sure if anyone else caught this old calculator dirty humor

    @ooples@ooples Жыл бұрын
    • Exactly

      @takeda3861@takeda3861 Жыл бұрын
  • Your videos are the best and I have learned so much from watching your videos. Keep up the fantastic work! I've been coding for over 30years and I'm still learning new tricks, thanks!

    @urbanguest@urbanguest Жыл бұрын
  • This was a great video. I love your little deep dives into the C# language.

    @GarethDoherty1985@GarethDoherty1985 Жыл бұрын
  • Great video! I certainly could have used this on previous projects but will make sure it gives me the benefits I need for my current ones.

    @spacetravelnerd6058@spacetravelnerd6058 Жыл бұрын
  • Can't express enough how amazing and educational your videos are. Keep doing what you do!!

    @Tal__Shachar@Tal__Shachar Жыл бұрын
  • .ForEach is not a LINQ method it is actually defined on List

    @Sahuagin@Sahuagin9 ай бұрын
  • I like how this channel gives a clear statement on what will be answered in a moment. Example: (1) At 1:12 Nick says, "I'm going to put all the ways to iterate over a list here" (2) This allows the user to pause the video and try and think of ways. (3) Then click play and view the 7 different ways. Its great that something like "Feel free to pause the video and try...." as most viewers know this and would not do it anyway. Side note - I was able to only think of three ways. (for loop, and forearch loop, ToArray().Select(x=>x) )

    @FunWithBits@FunWithBits Жыл бұрын
  • I've been a C# software engineer for a few years now and until this video I've never heard of a Span (outside the context of html lol). Going to be looking that up, great vid!

    @Zindawg02@Zindawg02 Жыл бұрын
  • That final console output is really good resume to keep in mind the use of iterations in c#. Very useful 👏👏

    @sergiom.954@sergiom.954 Жыл бұрын
  • Great benchmark. Good that you explained that the parallel versions are most likely faster when you actually do work inside the iterations. It always distracts me when you say "half the speed" when you mean "half the time" (ie. double the speed). I know it might be a language thingy, but it is really confusing at times.

    @ristopaasivirta9770@ristopaasivirta9770 Жыл бұрын
    • Oh damn you are right. I was thinking it in my head in Greek. In English it doesn't really make sense.

      @nickchapsas@nickchapsas Жыл бұрын
    • @@nickchapsas Oh wait,so you are actually Greek huh?

      @ZeroSleap@ZeroSleap Жыл бұрын
    • @@ZeroSleap Yeap

      @nickchapsas@nickchapsas Жыл бұрын
    • Actually I'm not sure we say that in Greek either 🤔 Haha very confused

      @unskeptable@unskeptable Жыл бұрын
    • He a bit geeky, he a bit Greeky

      @LordErnie@LordErnie Жыл бұрын
  • Very detailed and helpful showing you the results of the typical options Andrew ones I had not seen before

    @itaylorm@itaylorm3 ай бұрын
  • Love these kind of videos, and so well explained!

    @tronaitor0@tronaitor0 Жыл бұрын
  • Didn’t know about Span(), never would have thought to look, foreach was already heaven, thank you. I was taught never add or remove items during a for loop but dd it anyway, then fast forward to writing multithreaded applications and foreach and Span() throwing an exception is a useful indicator of faulty design.

    @paulembleton1733@paulembleton1733 Жыл бұрын
  • Very interesting to learn this, I could use this in my project. Thanks Nick

    @coding-gemini@coding-gemini Жыл бұрын
  • Fantastic video, great info and very clear. Learned a lot. Subscribed.

    @rogerdeutsch5883@rogerdeutsch5883 Жыл бұрын
  • Interesting. I could use this to speed some things up. Seems pretty niche for most of what I do tho, but definitely an improvement where improvements can be made

    @hipihypnoctice@hipihypnoctice Жыл бұрын
  • Nick is a legend. Integrating "easter eggs" like 69, 1337 and 80085 always makes me smile

    @user-zh3el2yr6h@user-zh3el2yr6h Жыл бұрын
  • LINQ doesn't have a ForEach extension method. What's being used in the video looks like the ForEach method defined by List.

    @jondoty@jondoty Жыл бұрын
  • I'm watching this for fun, it's legit fun to watch. Hat's off

    @stephencollis1453@stephencollis1453 Жыл бұрын
  • Great video as always! I also did some collection benchmarks back in April 2022, and i found something different than your benchmarks: for loops were considerably faster than foreach loops. The problem in your benchmark code might be that you access the private field instead of using a variable. foreach will automatically inline the field access to a variable, but for does not do that. In my benchmarks, foreach loops on List were 50% slower than for loops.

    @IAmFeO2x@IAmFeO2x Жыл бұрын
    • It looks like this got optimized in .NET 7

      @nickchapsas@nickchapsas Жыл бұрын
    • Yep, made similar benchmark tests and in dotnet 6 for 100k iterations and foreach took 75 us, for took 37us and Span Foreach 24us. Nice to see that dotnet 7 has many hidden performance boosts!

      @MaxReble@MaxReble Жыл бұрын
    • @@MaxReble Yep, can confirm, too: I reran my tests with .NET 7 RC1 and for and foreach loops are now nearly identitcal in speed. Still nearly twice as slow as iterating over arrays, spans, or ImmutableArray.

      @IAmFeO2x@IAmFeO2x Жыл бұрын
    • Should be parallel unless future iterations/loops are impacted by previous ones IMO. Going for the fastest synchronous/sequential approach is a great exercise, but independent iterations are the perfect Use Case to be done in parallel.

      @aurinator@aurinator Жыл бұрын
    • It might be a good idea to add a benchmark consumer type to actually consume the iteration result to make sure nothing gets optimized away

      @marbachdaniel@marbachdaniel Жыл бұрын
  • Oh wow! didn't know about this. Thank you so much

    @zacky7862@zacky7862 Жыл бұрын
  • Good point man. Thanks for the video.

    @vladkorsak2163@vladkorsak2163 Жыл бұрын
  • Excellent find. Thank you

    @cdarrigo@cdarrigo Жыл бұрын
  • Always great info man.

    @slipoch6635@slipoch6635 Жыл бұрын
  • Very interesting. Thanks for this!

    @franciscovilches6839@franciscovilches6839 Жыл бұрын
  • That is awesome! Thanks Nick

    @Sky4CE@Sky4CE Жыл бұрын
  • Great video, glad I found you.

    @beecee793@beecee793 Жыл бұрын
  • As always , thanks Nick

    @neotechfriend@neotechfriend2 ай бұрын
  • What a great video and information for iterating a List !! I think that this works with a List of object that has plenty of properties...

    @miguelfajardo8236@miguelfajardo823611 ай бұрын
  • This helped a lot thank you

    @docleoyeo@docleoyeo Жыл бұрын
  • A nice extension method is in order :D public static void FastForEach(this List source, Action action) { var span = CollectionsMarshal.AsSpan(source); foreach (var t in span) { action(t); } }

    @LoKSET@LoKSET Жыл бұрын
  • This is the best free software Ive seen. Respect.

    @dawidopalinski702@dawidopalinski702 Жыл бұрын
  • Awesome video. Always learn something new.

    @Meta0Riot@Meta0Riot Жыл бұрын
  • As an old guy, I want to add that, if you don't care about the order of iteration (and all the parallel examples illustrate this is the case here), you can run the index backwards, which avoids calling Count, Size, or Length on each iteration: var asSpan = CollectionsMarshal.AsSpan(_items); for (int i = asSpan.Length; --i >= 0; ) { var item = asSpan[i]; } Note that I explicitly declared i as a signed type so the loop termination condition can be satisfied. Many of the other examples (not using Span) also fail if the collection is changed during the iteration. The difference is that with the cases that use an enumerator you deterministically get a specific exception, whereas with the Span you just get mysterious behaviour (which is also true for the direct indexing loop).

    @kevinmartin7760@kevinmartin7760 Жыл бұрын
    • Just a couple of days ago, I implemented a backward for loop similar to your example and it used a var for the index variable. I wonder if is it really worth using --i >= 0 ?

      @alexintel8029@alexintel8029 Жыл бұрын
    • @@alexintel8029 It depends on the actual processor, but on the ones typically used nowadays comparing the result of a computation with zero is faster because no compare instruction is required. The instruction for the computation (in this case likely a decrement instruction) will set flags in the processor indicating if the result was zero, negative, or the computation produced signed or unsigned carry/borrow/overflow, so it can be immediately followed by a conditional jump. If you separate the decrement from the compare, a decent optimizing compiler should be able to relocate them so the conditional jump is still right after the compare, for instance treating: for (int i = x; i >= 0; --i) {...} as: int i = x; if (i >= 0) do {...} while (--i >= 0); // which can again decrement and conditionally jump with no compare instead of the more direct int i = x; while (i >= 0) { ...; --i; } However if your exit condition compares with a value other than constant zero, as in for (int i = 0; i

      @kevinmartin7760@kevinmartin7760 Жыл бұрын
    • @@kevinmartin7760 Thanks for the explanation Kevin. I realise the beauty of your original example for (int i = asSpan.Length; --i >= 0; ) {...} It helps a) prevent accessing asSpan[asSpan.Length] which would lead to index out-of-bound error b) decrement the loop c) test for exit condition

      @alexintel8029@alexintel8029 Жыл бұрын
  • This is so much nicer than my in a pinch method: Compiled reflection accessing the array, then use that and the count to get a span. Probably a smidgeon faster too... Spans are amazing....

    @tobyjacobs1310@tobyjacobs1310 Жыл бұрын
  • Amazing stuff, thanks!

    @ivaniliev93@ivaniliev93 Жыл бұрын
  • Extra way: walk via unconditional (!) "for" loop, exit via catching "OutOfBounds" exception. Removes double-checking of bounds, but introduces overhead from exception handling. May outperform if the list is extremely huge (throw cost is constant and doesn't scale with items count).

    @bmazi@bmazi Жыл бұрын
  • Everything is cool! Thanks!

    @matejakendereski4264@matejakendereski4264 Жыл бұрын
  • There is one more way to iterate - using SIMD (Vector), which has lowest readability, but probably will have the best performance, because it's accelerated on hw level and CPU takes n items in processing at one CPU clock.

    @jackp3303@jackp3303 Жыл бұрын
  • Getting a local scoped reference to the array allows JIT to optimize away the range checks in the loop (technically also unroll but I don't think it does that). It's not possible for a list since there is no guarantee that other code somewhere wont change the length during our looping. But if you have an array, then length is fixed, and you can do a single if-check pre-looping instead of checking the bounds every iteration.

    @BadgersEscape@BadgersEscape Жыл бұрын
    • Interesting, this should also be possible for any foreach since the collection isn't allowed to change during the loop, but I guess .NET does not implement that optimization (yet).

      @TheMAZZTer@TheMAZZTer Жыл бұрын
  • This is really amazing Nick! Even in the things that seem so basic in simple, we are finding hidden gems!

    @hamedsalameh8155@hamedsalameh8155 Жыл бұрын
  • It was as expected. Nothing beats the standard WHILE loop except doing things in parallel - which comes with a lot of downsides.

    @redguard128@redguard128 Жыл бұрын
  • Probably the absolute winner: on Stackoverflow I found an example of doing parallel work on a Span, but it involves unsafe pointers, since the Span type itself cannot escape to the heap and therefore Parallel calls on it are normally not possible. I searched for this because I was curious why this ultimate combination was not metioned in the video.

    @jongeduard@jongeduard Жыл бұрын
    • You can actually combine Parallel.ForEach and Span without pointers. I did some benchmarks and it was faster than all of Nick's implementations @ 1 million elements. The trick is using Partitioner.Create(0, list.Count) and passing it to Parallel.ForEach along with a closure around list that takes a Tuple as parameter and marshalls list to Span, then slices it using the tuple and finally iterates over it.

      @pedroferreiramorais9773@pedroferreiramorais9773 Жыл бұрын
    • @@pedroferreiramorais9773 Oh great :), I really have to dive into that to understand how that works. Let's say that a very simple solution does at least not exist yet.

      @jongeduard@jongeduard Жыл бұрын
    • @@jongeduard well, you can create an extension method to encapsulate all the logic, but it loses much of the performance gain. It can still be better than sequential span iteration of very large lists/arrays, but if performance is the main concern, you often have to get your hands dirty.

      @pedroferreiramorais9773@pedroferreiramorais9773 Жыл бұрын
  • hi, great video as usual. Do you take topic suggestions? parallel.foreach vs parallel.foreachasync pls .. :)

    @chiragdarji1571@chiragdarji1571 Жыл бұрын
  • I rarely work with List, would have liked to see benchmarks with lists of classes. I feel like the results would be very different. Also please add disclaimers to your performance videos. Some might get the idea they should be using span loops everywhere.

    @haxi52@haxi52 Жыл бұрын
    • There is a similar performance improvement with other objects. The video does have a disclaimer too

      @nickchapsas@nickchapsas Жыл бұрын
    • I ran the test and on my machine results are as followed (with dotnet 7) List Iterate_ForEach | 49.71 us | 0.330 us | 0.276 us | - | Iterate_For | 40.59 us | 0.241 us | 0.213 us | - | Iterate_ForEach_AsSpan | 24.64 us | 0.129 us | 0.121 us | - | List Iterate_ForEach | 52.27 us | 0.634 us | 0.562 us | - | Iterate_For | 41.18 us | 0.477 us | 0.398 us | - | Iterate_ForEach_AsSpan | 25.33 us | 0.480 us | 0.426 us | - | So, I see a bigger difference between for and foreach as nick does, but the delta of for and foreach_asspan does not change.

      @MaxReble@MaxReble Жыл бұрын
  • Thanks! I wasn't aware of CollectionsMarshal!

    @yv989c@yv989c Жыл бұрын
  • This was really interesting. I've never seen the AsSpan methods before. I honestly had to look up what a Span was lmao.

    @DaveGouda@DaveGouda Жыл бұрын
  • Thank you!

    @ayudakov@ayudakov Жыл бұрын
  • Outstanding comparison. 5 stars

    @GregUzelac@GregUzelac Жыл бұрын
  • How much time did you train to talk so fast and clearly at the end of the video? I really thought that I knew how to iterate... thanks for always taking our code to the next level

    @brunodossantosrodrigues5049@brunodossantosrodrigues5049 Жыл бұрын
  • i think the unsafe part is fine and expected, foreach breaks if you add/remove elements during a loop as well.

    @KineticCode@KineticCode Жыл бұрын
    • That's true. But what if we mutate objects of the list. Say, a person from List while looping. Foreach allows this - will this span approach too?

      @RahulSingh-il1xk@RahulSingh-il1xk Жыл бұрын
    • @@RahulSingh-il1xk Obviously not on values that you access during the iteration. What I am interested in is what happens if I mutate values, that are not accessed during the iteration.

      @PetrVejchoda@PetrVejchoda Жыл бұрын
    • Guys I think you can mutate objects :) its not a readonly span, just a span

      @KineticCode@KineticCode Жыл бұрын
    • because foreach breaks if the list is mutated then they should just make foreach compile into the unsafe part

      @Crozz22@Crozz22 Жыл бұрын
  • Brilliant!

    @lancemarchetti8673@lancemarchetti8673 Жыл бұрын
  • The puts so much perspective on things 😅

    @CricketThomas@CricketThomas Жыл бұрын
  • I use Parallel when the tasks are small in number and heavy. I have an app that does six similar tasks, each taking about 500 ms, and it's great. If you needed 3000 ms instead by doing 3000 tasks that each take 1 ms, the overhead of creating each instance makes it a close call. If it's 3,000,000 jobs that each take 1 us, then I definitely would not parallel.

    @karldavis7392@karldavis7392 Жыл бұрын
  • To span a loop into a 13 minute video, that's what I call a great job! lol

    @SergeDuka@SergeDuka Жыл бұрын
  • ForEach is list method, not linq method. Span forbids only adding and removing of items, but not assigning. And also I don't like benchmarks that don't use data. Some optimizer can remove more than expected. You've shown IL, but it doesn't garantee jit won't change smth. 9:26 How can 1 byte be allocated?

    @QwDragon@QwDragon Жыл бұрын
    • I assume there are cases when compiler (jit) can infer that it's safe to use span for list traversal.

      @VoroninPavel@VoroninPavel Жыл бұрын
    • malloc(1)

      @2003vito@2003vito Жыл бұрын
    • 1 byte is allocated because the JIT allocates, and the benchmark picks it up. That allocation is removed in .Net 7. You can read more about it on the benchmarkdotnet repo. It's actually more than 1 byte allocated, but the benchmark divides it by how many iterations were ran. [Edit] Actually, the rogue allocation still seems to be showing up in Net 7, but the cause hasn't been looked into yet.

      @protox4@protox4 Жыл бұрын
    • @@protox4 Thanks for pointing out is is averaged.

      @QwDragon@QwDragon Жыл бұрын
  • Brilliant 💪

    @ayhamala3ma189@ayhamala3ma189 Жыл бұрын
  • Thank you!

    @titiksasanti2205@titiksasanti2205 Жыл бұрын
  • To complete the big picture, You can add Enumerator + While( list.MoveNext()){bla-bla-bla} some tests say that it more efficient than foreach/for but not so efficient as a span

    @justengineering1008@justengineering1008 Жыл бұрын
  • This is super interesting! I never learned about "spans" in any school, I don't even know what it is! I will eventually google it but could you elaborate quickly in case my laziness gets the better of me? 😅Thanks!

    @deus_nsf@deus_nsf2 ай бұрын
  • Watching your videos makes is very humbling and makes me realise that I'm absolutely shit at my job!

    @Evan-zj5mt@Evan-zj5mt Жыл бұрын
    • Nah trust me you don’t need to know 99% of the stuff I show to be good at your job

      @nickchapsas@nickchapsas Жыл бұрын
  • It was funny when I rolled my eyes before you said “Of course it would be a span” and started giggling 😂😂

    @user-lf5sy5mv3l@user-lf5sy5mv3l Жыл бұрын
  • When a program's performance tests are below client's expectations, would you always go for a Span refactorization? ...assuming that no major blunder was made like a bad algorithmic complexity.

    @nickst0ne@nickst0ne Жыл бұрын
  • I will give you a little tip, on the List as Span method you can actually use it to modify the items with ref, like: var listSpan = CollectionsMarshal.AsSpan(list); foreach(ref var item in listSpan) { // You can modify 'item' here even if it is a struct }

    @diadetediotedio6918@diadetediotedio6918 Жыл бұрын
    • You don’t need ref to modify the items. You can just modify them. They are still references

      @nickchapsas@nickchapsas Жыл бұрын
    • @@nickchapsas No, if they are structs you will surely need ref, and if you want to "modify" immutable records too. Think in things like: foreach(ref var itemStats in item.Stats) { itemStats = itemStats with { Speed = 10 }; } You cannot do anything like that without refs.

      @diadetediotedio6918@diadetediotedio6918 Жыл бұрын
  • I am only 2 weeks into the learning how to code and actually learning c#. What you talking about and showing looks great and fun but it's to much for my brain is right now. Your videos are cool and very informative but just to advanced or geared to seasoned coders. But nice videos, one day I'll fully understand all the things you explain in your vids.

    @AaronMolligan@AaronMolligan Жыл бұрын
    • I’ve been programming for ten years and I have never heard of a span before

      @matthewjohnson3656@matthewjohnson3656 Жыл бұрын
    • @@matthewjohnson3656 Same here (25 years!) and just heard of a span a month ago (that isn't )!

      @davestorm6718@davestorm6718 Жыл бұрын
  • Thank you, I literally didn't even know about spans.

    @micmacha@micmacha Жыл бұрын
  • foreach statement cannot operate on enumerators of type 'Span.Enumerator' in async or iterator methods because 'Span.Enumerator' is a ref struct. Has that changed in .Net 7?

    @elpe21@elpe21 Жыл бұрын
  • Hi, great video! its so usefull. Thanks. I have a question, how can i implement it in async method? what is the best practices in async?

    @22Ericelcuervo@22Ericelcuervo Жыл бұрын
  • I doubt I'll ever use it, but quite amazing.

    @swordblaster2596@swordblaster2596 Жыл бұрын
  • Love your seeds

    @mykhailokonontsev3132@mykhailokonontsev3132 Жыл бұрын
  • Looking at the implementation of List.ForEach I don't understand why this one is so much slower than just the standard for. Is invoking an Action really that slow of an operation?

    @codemonkeyjesse@codemonkeyjesse Жыл бұрын
    • Yes and it is also prone to closures that can make the problem even worse

      @nickchapsas@nickchapsas Жыл бұрын
    • @@nickchapsas what if you make the lambda static

      @Crozz22@Crozz22 Жыл бұрын
  • Great video. could you make one video on Partitioner?

    @parthaf22@parthaf22 Жыл бұрын
  • INSANE!

    @irjgametube2995@irjgametube2995 Жыл бұрын
  • I would say that with the error listed, it is only the 100 item list that is different for the For and ForEach. You can even see that when you run all of them options, you get the order the other way around for the 1 million item list.

    @jeffreyblack666@jeffreyblack666 Жыл бұрын
  • Calling it before watching the video: CollectionsMarshal.AsSpan() Edit: Called it. I would've also liked to see a benchmark which uses the list cast to an IEnumerable, then the IEnumerator would be an interface variable instead of a stack struct which would slow things down because of dynamic dispatch.

    @petrusion2827@petrusion2827 Жыл бұрын
    • Hey I can see that you skipped forward 👀

      @nickchapsas@nickchapsas Жыл бұрын
    • @@nickchapsas Oh yeah I didn't have time to watch the whole video from start to finish, I used KZhead's 10 second skips to go through the most relevant parts, but only after I made the comment :D Nice vid for sure

      @petrusion2827@petrusion2827 Жыл бұрын
    • @@nickchapsas you haven't shown foreach on IEnumerable in the video.

      @QwDragon@QwDragon Жыл бұрын
  • Nice. Ty

    @T___Brown@T___Brown Жыл бұрын
  • 1:35 Nice seed value :)

    @gergelycsaba5008@gergelycsaba5008 Жыл бұрын
  • Nice video. I am also interested if there are any actual difference between Span and an Array, which in my opinion should perform more like the same.

    @RCYmacau@RCYmacau Жыл бұрын
    • There is a difference indeed. I’ve covered this in the dedicated span video if I remember correctly

      @nickchapsas@nickchapsas Жыл бұрын
    • @@nickchapsas there will be no performance difference iterating Array vs Span, and why would there be - both represent contiguous memory with minimum overhead. List is a different story because it has some additional logic, and you are paying the (small) price for it.

      @user-pn1gt2km5r@user-pn1gt2km5r Жыл бұрын
    • @@user-pn1gt2km5r Actually there is. I also have noticed that

      @renauddanniau676@renauddanniau676 Жыл бұрын
  • @Nick, I'm curious if you've ever encounter a Duff's Device in C# and if you would consider it to benchmark it as well. I would be delighted to see it compared to the span. Thanks for this video in any case.

    @aschwinwesselius@aschwinwesselius Жыл бұрын
    • C# Syntax is much more restrictive than C, it won't allow the original Duff's Device. And, tbh, I'm rather happy about that. 🙂

      @MarkusSchaber@MarkusSchaber Жыл бұрын
  • Great Thanks

    @ahmedseada7371@ahmedseada7371 Жыл бұрын
  • The only approach that doesn't throw an exception if the collection changes, at least as far as I know, is a for loop. Anything that uses an iterator will throw because the MoveNext method checks the version. So that covers foreach and the List.ForEach methods at least. The parallel ones almost certainly won't handle a collection change during iteration. Most of the time, changing a collection while iterating over it in any way is undesirable.

    @ItsTheMojo@ItsTheMojo Жыл бұрын
  • Very interesting stats here

    @nove1398@nove1398 Жыл бұрын
  • Your channel is a pot of gold for me as a bad C# developer ⭐

    @Faygris@Faygris Жыл бұрын
  • Foreach also has the same limitation, can't add or remove from the list, then we can replace each "foreach" with span version?

    @ceosmangumus@ceosmangumus Жыл бұрын
  • Great video! I'm curious, is Span still faster if there's heavy processing of the data done inside the loops? What if (as a separate question) you were to perform async operations like retrieving data from a DB inside your parallel loop, implemented with the Parallel.ForEachAsync method? How does it compare when just using Span?

    @zagoskintoto@zagoskintoto Жыл бұрын
    • You can’t use await in a method that uses spans

      @ImmoLandwerth@ImmoLandwerth Жыл бұрын
  • I'm pretty surprised, so they optimised out the allocation of the foreach enumerator? And somehow also eliminated the overhead of its constant 'version' checks (to stop changes mid iteration)? I wonder if this is a consequence of that 'sealed' keyword you mentioned the other day, or if other work also went into it

    @billy65bob@billy65bob Жыл бұрын
    • They did optimise it in .NET 7

      @nickchapsas@nickchapsas Жыл бұрын
  • How in the world do you find this stuff? 🤔 great video by the way ;)

    @TheCoastpear@TheCoastpear Жыл бұрын
  • If you are algorithm is loop heavy, you can use loop unrolling for more speed.

    @engineeranonymous@engineeranonymous Жыл бұрын
  • Wow impressive results, depending on what work you need to do within the loop, a Parallel span loop might be good.

    @harag9@harag9 Жыл бұрын
    • See my other reply, it's not possible without unsafe pointer tricks, due to the fact that a Span cannot escape to the heap. It simply won't compile. Parallel loops make use of callbacks (delegate, lambda, which is basically a reference type object) and therefore need an allocation in the managed heap.

      @jongeduard@jongeduard Жыл бұрын
    • @@jongeduard Ahh thanks. I've never used a span - still use 4.8 :(

      @harag9@harag9 Жыл бұрын
    • @@harag9 Someone else replied to my other command that it is actually possible. :P Something with Partitioner.Create and a Tuple. I would still need to dive into that one and try it myself to better understand it. Let's conclude that a simple solution does at least not exist.

      @jongeduard@jongeduard Жыл бұрын
  • 80085, I see a man of refined culture. 😅☺️

    @AbhinavKulshreshtha@AbhinavKulshreshtha Жыл бұрын
    • The zip code of the Simpsons' home town Springfield.

      @krccmsitp2884@krccmsitp2884 Жыл бұрын
    • @@krccmsitp2884 I didn't knew that.. I was thinking about the old calculator trick we used to do in schools during mid 90s, when we first got to use them.

      @AbhinavKulshreshtha@AbhinavKulshreshtha Жыл бұрын
    • @@AbhinavKulshreshtha Well, that's the other meaning. I know that trick too and what you wanted to indicate. :-)

      @krccmsitp2884@krccmsitp2884 Жыл бұрын
  • It's nice that you check the IL code, but what about the JIT?

    @MarkusSchaber@MarkusSchaber Жыл бұрын
  • I did not expect to wake up this morning and be surprised by a genuinely faster way to iterate a list, one of the most common tasks in software development.

    @CharlesBurnsPrime@CharlesBurnsPrime Жыл бұрын
  • Nice one, could help increase complex reporting.

    @markharby180@markharby180 Жыл бұрын
  • Hello! At my job, we had an ague with colleagues what is better if you need to represent a collection in your DTO: List or Array. I think array is better. I had my own bunch of arguments about this, but would love to listen to your opinion about this question. Is there any chance you will make a video with close topic?

    @user-qf2xk1fg6e@user-qf2xk1fg6e Жыл бұрын
    • depends on the usage. For DTOs (since there is no mutations) I prefer to use IEnumerable (most of the time) because it's implemented on almost all collections (Arrays, Lists ..etc). This makes things much easier to work with, and to avoid adding more memory overheads. If you want to only read, then just iterate. If you want to mutate, then copy it to any desired collection type (ToList, ToArray, ToHashSet ..etc.).

      @Isr5d@Isr5d7 ай бұрын
  • I wonder, can you mutate the list when other iteration methods are used? No side effects expected?

    @B08AH@B08AH9 ай бұрын
  • I see what you did with the Seed :D

    @somebodystealsmyname@somebodystealsmyname Жыл бұрын
  • So only way to grantee the collection is not mutated while using CollectionMarshal is to lock it? Or would it be safe to use if I wanted, let's say get a list of Entities I wanted to write out on a page? I mean, what collections couldn't be mutated at any given time when you haven't locked it?

    @darkclove7365@darkclove7365 Жыл бұрын
  • fascinating..

    @ayotundeayoko5861@ayotundeayoko5861 Жыл бұрын
  • impressive

    @geforcesong@geforcesong Жыл бұрын
KZhead