Writing C# without allocating ANY memory



Check out my courses: https://nickchapsas.com
Become a Patreon and get source code access: https://www.patreon.com/nickchapsas

Hello everybody I’m Nick and in this video I will show you how you can use features such Span, ReadOnlySpan and stackalloc to write allocation free C# that is very fast. This video will just focus on a single example but I will explain every decision as I go and hopefully you will find areas where you can use the technique you see here to optimize your own code.

Don’t forget to comment, like and subscribe 🙂

Social Media:
Follow me on GitHub: http://bit.ly/ChapsasGitHub
Follow me on Twitter: http://bit.ly/ChapsasTwitter
Connect on LinkedIn: http://bit.ly/ChapsasLinkedIn

Keep coding merch: https://keepcoding.shop

#csharp #dotnet #performance

23 Comments

  1. Hi, i wont to send GzipCompressed data Stream to RabbitMQ body message, which accept ReadOnlyMemory<byte>. Is any way to convert Stream to ReadOnlyMemory<byte> with minimum memory allocation?

  2. Thanks for the video.
    I really appreciated it that they introduced this modern style of the good old stack-based buffer programming into the "safe" area of C# programming language, it's only just a few years ago.
    As somebody who also programs in the classical C and C++ languages at certain times, I know exactly what these things mean. Everything is stack-based there by default. Very different from .NET and that makes these languages incredibly performance efficient.
    I suspect that many daily C# development may bennefit more often from these things than we are often aware of.
    We are all so used to the traditional heap reference based based array's in .NET.

  3. Some tips on this video:
    1) there is a Guid.TryWriteBytes() method that acts without allocation
    2) you can use string.Create() to fast allocate the strings based on Span<char>, instead of calling string constructor

  4. While stackaloc isn't unsafe, unsafe.
    As far as I recall if you misuse it you could make it do an overflow which is not catchable and will just crash the entire app.
    You mention this at the end.

  5. I would be interested in seeing json serialization/deserialization techniques that are more memory efficient. Especially when receiving back large json payloads that need to be deserialized to an object.

  6. It remained unclear how to apply this content in real life. I would like to retreive some data from SQL database to an array and to perform some fast calculations without allocating the heap memory. Does the stackalloc command help in this case to achieve better performance?

  7. Tip: Theres a static class called "WebEncoders" in .Net (using Microsoft.AspNetCore.WebUtilities) that can "Base64UrlEncode()", so you dont need to create your own base64 url encode function yourself.

Leave a Reply

© 2023 53GB