How to Use Spans in C-Sharp ( Stackalloc, Heap and Stack Memory)


Read about Spans (They are faster than Strings in C#)

1. Learn to use Spans<byte> instead of String. When you use Spans there is no memory allocation on the HEAP memory that meas Garbarge Collection won't be able to track Spans. Spans are short leaved, they get allocated on the STACK Memory and can only be accessed by one Thread at the time so that makes Spans Thread Safe.
Spans are faster that String.
Read this Article


- Why would you want to use Span instead of Strings?
      - Strings are stored on the Heap Memory that means that if there are many String objects it might trigger a Garbage Collection. 
        - Everytime you want to retrieve a String value, a new Object is created on the Heap just to retrieve that String value. This might halt the memory and trigger a GC

Solution: If you want to optimize for perfomance use a StringBuilder() that uses an internal buffer when you want to concate value to a String.
- User a String.Create() function to create an object of a String on Runtime which will not be stored on the Heap Memory but on a Heap but explicitly set the size.


Facts about Stack Memory
1. When you create an object and assign it to another object, you are creating a  pointer to the memory locaton where the Object is currently stored.
e.g. string a = "hello":
         string b = a;

2. Stack Memory can only be accessed by the Owner Thread

3. Stack Memory only stores reference to the Object stored on the Heap Memory instantieted by using a new keyword.
4. 

Warning about using Span<> and stackalloc

1. The amount of memory available on the stack is limited, therefore if you alocate alot of memory on the Stack you will have a StackOverflow Exception.
   - Do not make size of allocation dynamic (based on the list length) instead make it a constant.
     - Do not use stackalloc inside a loop, allocate memory outside of a loop and reuse it inside the loop.
      - Use Span<T>.Clear to set the memory to default allocaton.
e.g. Span<MyObject> instance = stackalloc TypeOfObject<MyObject>







For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email AddressContact: [email protected]