The Fastest Way to Modify a List in C# | Coding Demo

  Рет қаралды 27,066

Zoran Horvat

Zoran Horvat

Күн бұрын

Пікірлер: 38
@zoran-horvat
@zoran-horvat Жыл бұрын
Become a patron and get access to source code and exclusive live streams: www.patreon.com/posts/fastest-way-to-c-81380759
@gahshunker
@gahshunker 6 ай бұрын
When you start understanding Zoran’s videos slightly better, is when you know you are becoming a slightly better developer.
@sealsharp
@sealsharp Ай бұрын
I like how you make a lesson on C# sound like a story.
@muhammedemin6842
@muhammedemin6842 2 жыл бұрын
I really like your teaching syle and examples. I used spans on a project yesterday and I've seen the difference. Thanks a lot, you are great! 🙌🏻👏🏻
@zoran-horvat
@zoran-horvat 2 жыл бұрын
I am just about to apply spans to a large code base. I was postponing that process, because it will not be easy to complete - but with expected 50%+ reduced execution time, the decision is clear...
@ml_serenity
@ml_serenity 6 ай бұрын
I really like your accent and the clarity of your explanations. Earned a sub! One another great things about Spans is how they reduce the memory allocations which is very important for server scenarios.
@timur2887
@timur2887 10 ай бұрын
spans are ref structs, containing a pointer to data and a length for its slice, so they allocated on stack only
@michaltomorowicz596
@michaltomorowicz596 2 жыл бұрын
Great video, many thanks. Really appreciate mentions of not only the perf gains but also the potential dangers of this approach... Looking forward to the future content already!
@10199able
@10199able 2 жыл бұрын
I find spans very helpful during string manipulation, because I dont have to create new strings on the heap :)
@zoran-horvat
@zoran-horvat 2 жыл бұрын
True, string class is imposing needless overhead, and it is often paid in bulks. String manipulation was a recurring topic at the time when spans first appeared.
@holger_p
@holger_p 4 ай бұрын
But you manipulate a self created char[] maybe with stackalloc. The string class still is immutable.
@bfrytech
@bfrytech 4 ай бұрын
Very nice, I've never used Slice(). Always figured spans were immutable so I never had any use for them.
@holger_p
@holger_p 4 ай бұрын
Cause Slice creates another, new Span. We just have to get used to the idea, creating a span is like writing "int i", not really what we consinder an "allocation".
@Sp1tfire100
@Sp1tfire100 Жыл бұрын
Great and easy to understand explanation. Thanks a lot👍
@julianocs87
@julianocs87 Жыл бұрын
Great video. Interesting insights on Spans. I'm always looking for opportunities to use them.
@leethompson1216
@leethompson1216 7 ай бұрын
Thanks a lot - Great explanation!
@wboevink
@wboevink 5 ай бұрын
You are also benchmarking foreach vs a for loop. Won't the compiler optimize an empty for(each) loop?
@muhammedalikhan7559
@muhammedalikhan7559 11 ай бұрын
Legend! ❤
@matheosmattsson2811
@matheosmattsson2811 Жыл бұрын
Good video! This may be a stupid question, but how does creating a Span from a list not allocate any new memory if the List is originally on the Heap but a Span is always on the Stack? I may have misunderstood something (probably), but could you briefly explain what happens during that "conversion"? Is the List copied from the Heap to the Stack or is the Span on the Stack just referencing memory on the Heap?
@zoran-horvat
@zoran-horvat Жыл бұрын
You have some good questions here, and I will try to give a short answer. Nevertheless, I would suggest that you read the documentation for spans very carefully. Span is a struct on the stack which only references (inside!) An array on heap. That prevents collection of the array and lets you perform optimized operations using that span, faster than using regular access. There are many consequences. One is that changing the list may cause the list object to reference a new array in memory while span still holds the old one. You may think you are modifying the list, but you are not. As soon as the span goes out of scope, the old array will be subject to collection.
@matheosmattsson2811
@matheosmattsson2811 Жыл бұрын
@@zoran-horvat Thank you for the quick answer :) So a Span is simply a struct containing pointers and basic logic for reading (and modifying) already allocated memory through references? If I understand correctly :D I will read up on spans!
@Wil_Bloodworth
@Wil_Bloodworth 8 ай бұрын
You might want to read the Liskov Substitution Principle again as it only applies to derived/child classes not just any general substitution. Span does not inherit/derive from List so this has nothing to do with the LSP principle and you're not violating LSP with your example. Maybe Barbara watches your channel and she can comment. LOL
@zoran-horvat
@zoran-horvat 8 ай бұрын
LSP is not about classes but about types. So much about who should read the principle again. Regarding my video, I am not sure which timestamp in the video you are referring to. Before clarifying, be aware that assigning a list to a span without recreating the object makes the list a subtype of a span, quite formally. It is the same effect as what you would accomplish by defining a custom implicit cast operator without a direct subclass relationship. Any cast operation defines a subtype relationship, and implicit cast does that with full formality. Now with a lowered cynicism on your side and more seriousness, I would like to hear which timestamp in the video should cause concern.
@_NguyenManhToan_
@_NguyenManhToan_ Жыл бұрын
Thank you very much!
@_NguyenManhToan_
@_NguyenManhToan_ Жыл бұрын
Great video ❤❤❤❤❤❤
@mumk
@mumk 10 ай бұрын
interesting video, thank you sir
@srkidd12
@srkidd12 Жыл бұрын
What about altering properties in the items that are within the Span? That likely ok? Not removing/adding items themselves.
@zoran-horvat
@zoran-horvat Жыл бұрын
Span is just a reference to an array. It doesn't cause reallocation of the array, but only gives you access to the elements. In that light, only getting or setting the values through the span does not cause any issues.
@quantume7143
@quantume7143 2 жыл бұрын
Great video! :)
@priyankapatil-w7s
@priyankapatil-w7s Жыл бұрын
i don't understand listofspan transform.. and whre is the actual implementation?
@icaroamorim3123
@icaroamorim3123 11 ай бұрын
cant use CollectionsMarshall
@anderspedersen2399
@anderspedersen2399 5 ай бұрын
Your benchmark is not really fair. You are accessing the array through the field every time, so you are forcing the compiler to generate code that reads the field every time the array is accessed (some other thread might have changed what _array is pointing to) and you are forcing the compiler to insert bound checks (again, the array used to calculate 'count' might be different from what _array is currently pointing to in each iteration). Normally, when accessing the same field multiple times in the same method, one would store it in a local variable, e.g. var array = _array. This lets the compiler know that the variable will not change for the duration of the method, so it can generate much more efficient code. If you do that, there is no good reason why the compiler shouldn't be able to generate equally efficient code for Spans and arrays.
@zoran-horvat
@zoran-horvat 5 ай бұрын
@@anderspedersen2399 The assumption of another thread is not plausible.
@anderspedersen2399
@anderspedersen2399 5 ай бұрын
@@zoran-horvat I know there will not be another thread that changes the value of _array in your benchmark, but the JIT compiler cannot know this, so by accessing the array through _array every time, you are forcing the compiler to generate worse code. The compiler is only looking at a single method at a time, and cannot make assumptions about the surrounding code.
@anderspedersen2399
@anderspedersen2399 5 ай бұрын
I just checked the generated assembly code on SharpLab and I was a bit wrong. The compiler is caching the reference to _array but is having trouble proving that _array.Length is constant, and keeps reading it from memory each iteration, rather than caching it in a register, which explains the speed difference. My suggested version, where _array is stored in a local variable does not have that problem and, by the looks of it, is generating better code than the Span version.
@zoran-horvat
@zoran-horvat 5 ай бұрын
@@anderspedersen2399 I think I mentioned the distinction between the external and local array variable, precisely with respect to checking the array's bounds.
@dotvkab
@dotvkab 8 ай бұрын
очередной маг выдает спаны за чудо божие 😂
Chain of Responsibility to the Rescue!
9:15
Zoran Horvat
Рет қаралды 13 М.
How to Avoid Null Reference Exceptions: Optional Objects in C#
18:13
Что-что Мурсдей говорит? 💭 #симбочка #симба #мурсдей
00:19
99.9% IMPOSSIBLE
00:24
STORROR
Рет қаралды 31 МЛН
The fastest way to iterate a List in C# is NOT what you think
13:42
Nick Chapsas
Рет қаралды 160 М.
3 Game-Changing Tips for Writing Simpler Code
12:30
Zoran Horvat
Рет қаралды 8 М.
What is Span in C# and why you should be using it
15:15
Nick Chapsas
Рет қаралды 264 М.
17 Pieces of C# Syntax That Make Your Code Short
12:41
Zoran Horvat
Рет қаралды 28 М.
Stackalloc and Spans
30:17
Coding Tutorials
Рет қаралды 12 М.
Settling the Biggest Await Async Debate in .NET
14:47
Nick Chapsas
Рет қаралды 149 М.
WHY IS THE STACK SO FAST?
13:46
Core Dumped
Рет қаралды 197 М.