{"id":353,"date":"2022-05-02T13:51:17","date_gmt":"2022-05-02T13:51:17","guid":{"rendered":"https:\/\/baldsolutions.com\/?p=353"},"modified":"2022-05-02T13:54:18","modified_gmt":"2022-05-02T13:54:18","slug":"stackalloc-buffer-on-the-stack","status":"publish","type":"post","link":"https:\/\/baldsolutions.com\/index.php\/2022\/05\/02\/stackalloc-buffer-on-the-stack\/","title":{"rendered":"Stackalloc &#8211; buffer on the stack"},"content":{"rendered":"\n<h1 class=\"wp-block-heading\">Introduction<\/h1>\n\n\n\n<p>Allocating some kind of a buffer (e.g. array) on a heap is a quite straightforward behaviour. It happens anytime we do something like this: <code>var array = new int[5]<\/code> . It is perfectly normal to use it &#8211; it is well known and intuitive solution. However, we can also allocate such a buffer on the stack. On the one hand it entails some risks,  but on the other it can safe some memory for us.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Stackalloc<\/h1>\n\n\n\n<p><a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/operators\/stackalloc\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Stackalloc\">Stackalloc<\/a> is an expression that allocates a block of memory on the stack. Thanks to that we can allocate a buffer on the stack instead on the heap. To do that we can use <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.span-1?view=net-6.0\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"Span\">Span<\/a> struct: <code>Span&lt;int> span = stackalloc int[7];<\/code>. The syntactic  seems to be pretty intuitive and understandable.<\/p>\n\n\n\n<p>BE CAREFUL: As it stands in the <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/csharp\/language-reference\/operators\/stackalloc\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"\">documentation<\/a>: &#8220;The amount of memory available on the stack is limited. If you allocate too much memory on the stack, a\u00a0<a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.stackoverflowexception\" target=\"_blank\" rel=\"noreferrer noopener\">StackOverflowException<\/a>\u00a0is thrown&#8221;. It is also important to mention that the <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.stackoverflowexception\" target=\"_blank\" rel=\"noreferrer noopener\">StackOverflowException<\/a> is kind of exception that cannot be caught. In other words, <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.stackoverflowexception\" target=\"_blank\" rel=\"noreferrer noopener\">StackOverflowException<\/a> = application termination. It doesn&#8217;t mean that it shouldn&#8217;t be used at all. It does mean that it should be used with great care and awareness.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Example<\/h1>\n\n\n\n<p>Let&#8217;s consider the following <code>StackallocExecutor<\/code> class:<\/p>\n\n\n\n<pre class=\"wp-block-code has-small-font-size\"><code>public class StackallocExecutor\r\n{\r\n    private readonly int _size;\r\n    private readonly Random _random;\r\n\r\n    public StackallocExecutor(int size)\r\n    {\r\n        _size = size;\r\n        _random = new Random();\r\n    }\r\n\r\n    public int Stackalloc()\r\n    {\r\n        Span&lt;int> span = stackalloc int&#91;_size];\r\n\r\n        for (int i = 0; i &lt; span.Length; i++)\r\n            span&#91;i] = _random.Next();\r\n\r\n        for (int i = 0; i &lt; span.Length; i++)\r\n            if (i % 2 == 1)\r\n                span&#91;i] += 1;\r\n\r\n        var max = span&#91;0];\r\n\r\n        for (int i = 1; i &lt; span.Length; i++)\r\n            if (span&#91;i] > max)\r\n                max = span&#91;i];\r\n\r\n        return max;\r\n    }\r\n\r\n    public int NoStackalloc()\r\n    {\r\n        var array = new int&#91;_size];\r\n\r\n        for (int i = 0; i &lt; array.Length; i++)\r\n            array&#91;i] = _random.Next();\r\n\r\n        for (int i = 0; i &lt; array.Length; i++)\r\n            if (i % 2 == 1)\r\n                array&#91;i] += 1;\r\n\r\n        var max = array&#91;0];\r\n\r\n        for (int i = 1; i &lt; array.Length; i++)\r\n            if (array&#91;i] > max)\r\n                max = array&#91;i];\r\n\r\n        return max;\r\n    }\r\n}<\/code><\/pre>\n\n\n\n<p>The class has two methods <code>Stackalloc<\/code> and <code>NoStackalloc<\/code>. Both of them do the the same &#8211; create a buffer, populate the buffer, add &#8220;1&#8221; to the odd indexes and return the max value. Maybe it is not the most real-world scenario but I hadn&#8217;t better idea at the time of writing the code\ud83d\ude01.<\/p>\n\n\n\n<p>Alright, but what&#8217;s the cool thing about the stackalloc at all? Let&#8217;s see the benchmark result!<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Benchmark<\/h1>\n\n\n\n<p>This time the crucial part of the results is the last column, i.e. &#8220;Allocated&#8221;.<\/p>\n\n\n\n<figure class=\"wp-block-image size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"666\" height=\"300\" src=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/05\/image.png\" alt=\"\" class=\"wp-image-358\" srcset=\"https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/05\/image.png 666w, https:\/\/baldsolutions.com\/wp-content\/uploads\/2022\/05\/image-300x135.png 300w\" sizes=\"auto, (max-width: 666px) 100vw, 666px\" \/><\/figure>\n\n\n\n<p>As you can see, no matter what the size of buffer is, the &#8220;Allocated&#8221; value for the <code>Stackalloc<\/code> method is the same. <code>NoStackalloc<\/code> method does quite the opposite, the greater size, the greater allocations.<\/p>\n\n\n\n<h1 class=\"wp-block-heading\">Summary<\/h1>\n\n\n\n<p>To sum up, having an ability to allocate reasonably small buffer on the stack seems to be interesting and useful feature. However, the <a href=\"https:\/\/docs.microsoft.com\/en-us\/dotnet\/api\/system.stackoverflowexception\" target=\"_blank\" rel=\"noreferrer noopener\">StackOverflowException<\/a> is still there and might kill the application without hesitation.<\/p>\n\n\n\n<p>As always I&#8217;ve prepared an example and you can find it on my <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"github\">github<\/a>, project: <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/stackalloc\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"arraypool\">stackalloc<\/a>, benchmark project: <a href=\"https:\/\/github.com\/tglowka\/baldsolutions\/tree\/master\/.NET\/stackalloc-benchmark\" target=\"_blank\" rel=\"noreferrer noopener\" title=\"\">stackalloc-benchmark<\/a>.<br>I encourage you to go through the code, debug it and try to test your own scenarios e.g. killing an application with StackOverflowException (for me the following throws the exception):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>var size = 1_000_000;\r\nvar executor = new StackallocExecutor(size);\r\nexecutor.Stackalloc();<\/code><\/pre>\n\n\n\n<p>Have a nice day, bye!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Allocating some kind of a buffer (e.g. array) on a heap is a quite straightforward behaviour. It happens anytime we do something like this:&#8230;<\/p>\n<div class=\"more-link-wrapper\"><a class=\"more-link\" href=\"https:\/\/baldsolutions.com\/index.php\/2022\/05\/02\/stackalloc-buffer-on-the-stack\/\">Continue reading<span class=\"screen-reader-text\">Stackalloc &#8211; buffer on the stack<\/span><\/a><\/div>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[2],"tags":[],"class_list":["post-353","post","type-post","status-publish","format-standard","hentry","category-net","entry"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/353","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/comments?post=353"}],"version-history":[{"count":13,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/353\/revisions"}],"predecessor-version":[{"id":367,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/posts\/353\/revisions\/367"}],"wp:attachment":[{"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/media?parent=353"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/categories?post=353"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/baldsolutions.com\/index.php\/wp-json\/wp\/v2\/tags?post=353"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}