<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergio Pedri on Medium]]></title>
        <description><![CDATA[Stories by Sergio Pedri on Medium]]></description>
        <link>https://medium.com/@sergiopedri?source=rss-138aedd31ff7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*4A0Ew4nTA1aRMrwd3-ciZg.png</url>
            <title>Stories by Sergio Pedri on Medium</title>
            <link>https://medium.com/@sergiopedri?source=rss-138aedd31ff7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:50:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergiopedri/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Announcing ComputeSharp 2.0 — run C# on the GPU with ease through DirectX 12 and D2D1!]]></title>
            <link>https://sergiopedri.medium.com/announcing-computesharp-2-0-run-c-on-the-gpu-with-ease-through-directx-12-and-d2d1-be4f3f2312b4?source=rss-138aedd31ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/be4f3f2312b4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[graphics]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[computing]]></category>
            <dc:creator><![CDATA[Sergio Pedri]]></dc:creator>
            <pubDate>Tue, 29 Nov 2022 13:37:52 GMT</pubDate>
            <atom:updated>2022-11-29T13:37:52.708Z</atom:updated>
            <content:encoded><![CDATA[<h3>Announcing ComputeSharp 2.0 — run C# on the GPU with ease through DirectX 12 and D2D1!</h3><figure><img alt="The wallpaper used as hero image for ComputeSharp on the GitHub repo. It has 3 images side by side, showing some blurred shader code, a GPU die, and an image resulting from applying a bokeh blur effect written with ComputeSharp on it. Over the image, at the center, is the project logo (a white grid icon with drop shadow over a blue background), and the “ComputeSharp” title right below it." src="https://cdn-images-1.medium.com/max/1024/1*l6IXKW4AIAl_-jsztHBfjQ.png" /></figure><p>After over 2 years of work, I’m happy to announce that ComputeSharp 2.0 is finally available! This is a complete rewrite of the library, featuring support for both .NET Standard 2.0 and .NET 6, new source generators to fully replace runtime code generation, a <strong>lot</strong> of new APIs, brand new support for D2D1 pixel shaders too, XAML controls for UWP and WinUI 3, and so much more! 🎉</p><p>A lot of effort has gone into this release, and the scope of the whole project has grown so much over time, way more than I had originally anticipated. In this blog post I want to introduce the library to those not familiar with it, highlight some of the new features, and show a few examples of what can be done with it.</p><p>For those that prefer a video form, <a href="https://youtu.be/kmXiV5TxBzs">here is a link to my talk about ComputeSharp at .NET Conf 2022</a>, and for those that just want to jump straight into the code, <a href="https://github.com/Sergio0694/ComputeSharp">here is a link to the GitHub repo</a> as well. Let’s jump into ComputeSharp 2.0! 🚀</p><p>Let’s start with an elevator pitch for the library: ComputeSharp is a .NET library to run C# code in parallel on the GPU through DX12, D2D1, and dynamically generated HLSL compute shaders, with the goal of making GPU computing easy to use for all .NET developers! It lets you write shaders (ie. code that can run on the GPU) using C#, and then it does all the heavy lifting to transform that code and actually dispatch it on the GPU in use on your machine. This can be used to hardware accelerate all sorts of workloads — image processing, parallel computations, generating fancy animations, you name it! And all without you needing to ever dive deep into the platform specific APIs necessary to make any of this work, nor to learn how to actually write HLSL, which is the programming language DirectX uses for shaders.</p><p>For a practical example, here’s the ComputeSharp Sample App in action:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FoNN1qsQeuRg&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DoNN1qsQeuRg&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FoNN1qsQeuRg%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/290c2bbcd143b4e8af5cc94c6b8dae64/href">https://medium.com/media/290c2bbcd143b4e8af5cc94c6b8dae64/href</a></iframe><p>Here you can see one of the XAML controls that ComputeSharp offers for UWP and WinUI 3 being used to render several animated compute shaders, in this case running into a WinUI 3 application. <a href="https://github.com/Sergio0694/ComputeSharp/tree/main/samples/ComputeSharp.SwapChain.WinUI">The entire source code is available on GitHub</a>, and all the shaders you see have been ported from GLSL shaders from <a href="https://www.shadertoy.com/">shadertoy</a> to just C#, and are all powered by ComputeSharp and running using DirectX 12 compute shaders.</p><p>And here’s another example of ComputeSharp in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B9Ntym7N1JTjXjZDwcy52g.png" /><figcaption>Paint.NET 5.0 showcasing a ComputeSharp-powered bokeh blur effect</figcaption></figure><p>I’ve spent the past few months adding Direct2D support to ComputeSharp as well, which is now a fundamental component of the upcoming <a href="https://forums.getpaint.net/topic/121340-paintnet-50-alpha-build-8361-welcome-to-paintnet-50/">Paint.NET 5.0 release</a>. ComputeSharp.D2D1 (the version of the library for D2D1 pixel shaders) is being used to implement dozens of image effects in the app, which are entirely written in C# and GPU accelerated through the power of D2D. This allowed <a href="https://twitter.com/rickbrewPDN">Rick Brewster</a>, the developer of Paint.NET, to greatly increase the number of effects he could run on the GPU, while at the same time significantly reducing the complexity of the application with respect to D2D GPU effects, as there was no longer the need to manually write effects in HLSL and compile them with a custom build step — ComputeSharp is doing all of this work behind the scenes!</p><blockquote>Fun fact — the bokeh blur showcased in the Paint.NET screenshot above is Rick’s port of my <a href="https://github.com/Sergio0694/ComputeSharp/blob/main/tests/ComputeSharp.D2D1.Tests/Effects/BokehBlurEffect.cs">ComputeSharp.D2D1 bokeh blur sample</a>, which is itself a port I did of my <a href="https://github.com/Sergio0694/ComputeSharp/blob/main/samples/ComputeSharp.ImageProcessing/Processors/HlslBokehBlurProcessor%7BTPixel%7D.cs">ComputeSharp bokeh blur sample</a>, which is a port from the <a href="https://github.com/SixLabors/ImageSharp/pull/842">C# version I wrote for ImageSharp</a>, which is a port from the Python version that <a href="https://youtu.be/vNG3ZAd8wCc">professor Mike Pound wrote for his Computerphile video on bokeh blur effects</a>. Go check it out!</blockquote><p>And this is also available for plugin authors, meaning that anyone can now also use ComputeSharp.D2D1 to write fully customized and GPU accelerated effects to integrate into Paint.NET. What used to require knowledge of HLSL and D2D internals is now easily accessible to all C# developers, with just a few lines of code and friendly, high-level APIs.</p><p>If you’re curious to see what a ComputeSharp shader looks like, here’s a very simple one: the hello world shader, which just displays an animated color gradient that changes over time. Here’s the C# code for it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pp-QuzZr9dh4IKlhuyD18g.png" /><figcaption>A DirectX 12 compute shader written in C# with ComputeSharp</figcaption></figure><p>You can see how the shader is simply a C# struct type, that captures some values (in this case a <strong>float</strong> to indicate the time passed), and then performs some computation to calculate the color to display in the output. This is the entire shader, which ComputeSharp will then take care of processing at build time through a source generator, to convert it to HLSL and also generate additional code to support its execution.</p><p>Here is what the resulting HLSL code looks like for this shader:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhFGUWarr__MLrMh-qW2iQ.png" /><figcaption>The transpiled HLSL shader for the C# type</figcaption></figure><p>It’s easy to see some of the transformations that ComputeSharp has done behind the scenes: the shader now has a constant buffer, which is used to marshal captured values to the GPU, it has thread size annotations to control the shader dispatching, automatic bounds checks have been added, and the shader is also implicitly capturing the output texture and assigning the resulting pixel to it. As a C# developer using ComputeSharp, you will never have to worry about any of this: the source generator bundled with ComputeSharp will take care of all this heavy lifting while you can write C# and benefit from IntelliSense and all the great tooling that C# offers.</p><p>I also want to show a couple of full end to end examples of what running code on the GPU using ComputeSharp looks like. We’ve seen how you can write a shader, but you might we wondering if dispatching it is actually difficult or not. It isn’t! And there’s also several ways to do that, so you can pick the one that best suits your needs as well.</p><p>ComputeSharp offers an eager execution mode, and a computational graph mode. The former is particularly useful if you’re just getting started with the library, want to try things out or just need to run some simple script and don’t want to have to worry about setting up a more complex execution pipeline. Here is how you can run a very simple test shader:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0CncwZ9jX5HZlzgKsMe-g.png" /><figcaption>Eager execution mode in ComputeSharp</figcaption></figure><p>That’s all you need to do to run C# code on the GPU! You can see how we have a very simple shader, which is just multiplying all values in a texture by 2, and then we’re dispatching it over a writeable buffer we allocated on the GPU with some random values in it. After dispatching the shader, we can also copy that GPU buffer back on the CPU so we can read its contents. ComputeSharp exposes dozens of very easy to use APIs to perform common operations like these, which can adapt to all scenarios from simple minimal scripts to more complicated architectures.</p><p>Let’s also look at an example using the computational graph mode:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jGzbd2SmLawfwBB7cl9Ctw.png" /><figcaption>Computational graph mode in ComputeSharp</figcaption></figure><p>This mode is perfect if you want to create a fully customized execution pipeline which can also squeeze the most performance out of the GPU. In this mode, we’re first creating a <strong>ComputeContext</strong>, which is an object that allows us to queue operations on the GPU. Then we’re creating our pipeline (including operations such as dispatching shaders, controlling transitions to synchronize accesses to shared resources, and more), and finally we’re dispatching that on the GPU when going outside the scope of the context. You can also see how here we’re leveraging the <strong>await using</strong> syntax to execute all this work asynchronously on the GPU, so we don’t block the current thread until the GPU finishes processing our request.</p><p>What about XAML support? ComputeSharp offers two controls (<strong>ComputeShaderPanel</strong> and <strong>AnimatedComputeShaderPanel</strong>), which make it super easy to integrate a ComputeSharp-powered effect into a UWP or WinUI 3 application: simply plop the XAML control into your view, assign a shader runner objec to it, and you’re good to go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCcZM7igkAVAO2gb_bQtCw.png" /><figcaption>ComputeShaderPanel used in a XAML view</figcaption></figure><p>Here’s how a <strong>ComputeShaderPanel</strong> can easily be declared within a view. Then, it just needs an <strong>IShaderRunner</strong> instance to know how to render each frame. For simple cases, for instance when we just want to display a shader animation, the built-in <strong>ShaderRunner&lt;T&gt;</strong> type is more than enough:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pfd_1cE5zMSRrdrwaiT0Uw.png" /><figcaption>ShaderRunner&lt;T&gt; being assigned to a ComputeShaderPanel</figcaption></figure><p>And that’s it! The panel will use the shader runner to draw each frame, and will take care of the entire setup needed to actually display each generated frame. For more advanced scenarios, you can also implement the shader runner yourself, which gives you full control over the frame timing, the computation graph used to produce each image to display, and more!</p><p>Finally, I also want to show an example of a D2D1 pixel shader. These are the shaders that Paint.NET uses, and they’re also part of the infrastructure I’m currently working on to enable using these into UWP and WinUI 3 applications through the Win2D library (you can see <a href="https://github.com/microsoft/Win2D/pull/888">my proposal for that here as well</a>). They’re vastly different than DirectX 12 compute shaders, but thanks to ComputeSharp’s infrastructure they’re just as easy to implement, and can also be run without too much effort by leveraging the built-in pixel shader effect that ComputeSharp.D2D1 includes.</p><p>Here’s an example of a pixelate effect from Paint.NET:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLu6pJlaOTi-C3lwGuFYFg.png" /><figcaption>A pixelate D2D1 pixel shader, from Paint.NET</figcaption></figure><p>You’ll notice there are some differences between this shader and the DX12 shader showed above, but the developer experience is mostly the same: you just need to author a C# type, use the available HLSL projections and APIs that ComputeSharp includes, let IntelliSense guide you, and then let ComputeSharp do all the rest of the work for you at compile time.</p><p>Let’s also look at the transpiled code for this shader:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vtQOj_9mQtQGxFwxhU7rKA.png" /><figcaption>The pixelate effect transpiled to HLSL</figcaption></figure><p>Once again, the C# type has been transformed as needed to follow the necessary HLSL conventions, in this case specifically for D2D1 pixel shaders. We have declared fields to map to the various captured values in C#, all intrinsics have been forwarded to their HLSL equivalents, the shader syntax has been updated, and much more. And all of these shaders, just like the DX12 ones, can also be precompiled at build time, meaning your applications can have blazing fast startup performance and no need to invoke or bundle the shader compiler at all once deployed!</p><p>There is much more that is available in ComputeSharp, and this is also just the very first stable release after the rewrite — there’s plenty of new features and improvements I’m already working on and that I plan to include in future releases! You’re welcome to <a href="https://github.com/Sergio0694/ComputeSharp">check out the repository on GitHub</a>, try out the library (<a href="https://www.nuget.org/packages?q=computesharp">you can find it on NuGet!</a>), and leave feedbacks and ideas!</p><p>And if you do use it and build something — please share it! I absolutely love to see all the cool things that people can build using ComputeSharp! 🙌</p><h4>Happy coding! 💻</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be4f3f2312b4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing the Microsoft.Toolkit HighPerformance 7.0 release]]></title>
            <link>https://sergiopedri.medium.com/announcing-the-microsoft-toolkit-highperformance-7-0-release-5f31079ae2be?source=rss-138aedd31ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f31079ae2be</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Sergio Pedri]]></dc:creator>
            <pubDate>Tue, 16 Mar 2021 16:44:22 GMT</pubDate>
            <atom:updated>2021-03-16T17:08:27.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mNCXH2er6IaJt_93_ka74Q.png" /><figcaption>Windows Community Toolkit — background and logo by .NET Foundation</figcaption></figure><p>The 7.0 update of the <a href="https://aka.ms/wct">Windows Community Toolkit</a> is finally available, including a huge number of new features (like the new <a href="https://aka.ms/mvvmtoolkit">MVVM Toolkit</a>, which we presented at .NET Conf), bug fixes and lots of changes and improvements also implemented thanks to the amazing support and feedbacks from the whole community. It also includes the second major public release of the <strong>Microsoft.Toolkit.HighPerformance</strong> package, with a large number of brand new APIs being included, performance improvements and .NET 5 support out of the box.</p><p>As a small recap on the <strong>HighPerformance</strong> package itself: this is a library part of the Windows Community Toolkit and targeting a number of different runtimes and profiles (ranging from .NET Standard 1.4 to .NET 5), that includes a collection of extensions and helper methods that can help when working on performance and memory usage critical applications. A brief introduction and the official docs are available <a href="https://docs.microsoft.com/windows/communitytoolkit/high-performance/introduction">in the MS docs</a> website.</p><blockquote>In this blog post I wanted to through some of the new features being included in this new version of the HighPerformance package, explain how they work and how they can be used to help in performance oriented scenarios 🚀</blockquote><h3>Memory2D&lt;T&gt; and Span2D&lt;T&gt; types</h3><p>T he <a href="https://docs.microsoft.com/dotnet/standard/memory-and-spans/memory-t-usage-guidelines"><strong>Memory&lt;T&gt;</strong> and <strong>Span&lt;T&gt;</strong></a> are two widely used types from the .NET BCL (Base Class Library) that implement a nice abstraction over arbitrary buffers, but they offer no way to properly extend that same level of abstraction to arbitrary 2D memory areas. This is both due to the fact that they lack useful helper methods and indexers to work in two dimensions, and because they inherit some restrictions from other parts of the ecosystem that make them not ideal for working with large underlying buffers, such as the fact that they can only store a length of size <strong>int</strong>. This becomes a particularly noticeable constraint when working in multiple dimensions, as it is easy to exceed the maximum supported value even with individual indices on each axis being relatively small. For instance, a 2D memory area of size 50.000x50.000 will be enough to exceed the <strong>int.MaxValue</strong> limit.</p><p>The <strong>Memory2D&lt;T&gt;</strong> and <strong>Span2D&lt;T&gt;</strong> types are meant to be a natural extension for <strong>Memory&lt;T&gt;</strong> and <strong>Span&lt;T&gt;</strong>, but working in 2 dimensions. They include several key features such as offering a flexible abstraction of <strong>discontiguous buffers</strong> due to their ability to slice 2D memory areas, meaning that each row might not be adjacent to the end of the previous one. They also do not share the same <strong>int.MaxValue</strong> limitation as standard BCL types — while the length of each axis is still restricted to <strong>int</strong> for consistency with .NET arrays, the total size is exposed as a <a href="https://docs.microsoft.com/dotnet/csharp/language-reference/proposals/csharp-9.0/native-integers"><strong>nint</strong></a> value. All the internal indexing operations are performed using <strong>nint</strong> values too, so that on 64 bit architectures it is possible to index much larger memory areas than it was before.</p><p>Since one line of code is worth a thousand words, here is an example of how all these various APIs can be used to perform different operations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/285818dccb390a585a2de93f5f9d73d5/href">https://medium.com/media/285818dccb390a585a2de93f5f9d73d5/href</a></iframe><p>These are just some of the features enabled by these new types, and there’s plenty more available APIs that can be used to easily work with these new types as well as to interoperate with the existing types from the BCL!</p><h3>StringPool</h3><p>The <strong>StringPool</strong> type implements a fast, thread-safe and configurable pool for <strong>string</strong> instances, using a least recently used (LRU) caching policy. It can be used to minimize allocations when creating multiple <strong>string</strong> instances from buffers of <strong>char</strong> or <strong>byte</strong> values, for instance when parsing text documents with many repeated values, like a CSV database, or when parsing tokens from web requests. It provides a mechanism that is somewhat similar to <a href="https://docs.microsoft.com/dotnet/api/system.string.intern"><strong>string</strong> interning</a>, with the main differences being that the pool is configurable, can be reset, is implemented with an automatic replacement policy and doesn’t require to pre-instantiate <strong>string</strong> objects, so it can save the initial allocations as well when working on temporary buffers.</p><p>We put this to the test with a benchmark parsing the <a href="https://github.com/dotnet/machinelearning/blob/master/test/data/taxi-fare-train.csv"><strong>taxi-fare-train.csv</strong></a> file, a 24MB CSV database from <a href="https://github.com/dotnet/machinelearning/"><strong>dotnet/machinelearning</strong></a> containing many duplicated text labels. The full benchmark gist can be found <a href="https://gist.github.com/Sergio0694/c51cb027e6815d7b592484eebe9e3685">here</a>, but the important bit is the difference in code to parse each <strong>string</strong> value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef2d2f98b4031c0ace52d4f8072d9c43/href">https://medium.com/media/ef2d2f98b4031c0ace52d4f8072d9c43/href</a></iframe><p>Here <strong>StringPool</strong> will take care of transcoding the input UTF-8 sequence into UTF-16 (working on buffers rented from a pool), and then it will try to find an existing <strong>string</strong> instance matching that content. If it is found, its timestamp is updated and that instance is returned, otherwise a new one is created and added to the internal map. This is all completely transparent to users, that just need to change a single line in this case. This is just one of the available <strong>StringPool</strong> APIs — there are overloads taking a <strong>ReadOnlySpan&lt;char&gt;</strong> as input (and doing no transcoding), or a <strong>string</strong> (similarly to how <a href="https://docs.microsoft.com/dotnet/api/system.string.intern"><strong>string.Intern(string)</strong></a> works), and more. For now, let’s look at a benchmark to see how this change changed the performance and memory usage of our code (using both the two possible solutions displayed above):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e1cd68f68938f00bf18b16172bb7c95/href">https://medium.com/media/2e1cd68f68938f00bf18b16172bb7c95/href</a></iframe><p>We can see that the performance is just a bit worse when using <strong>Encoding.UTF8</strong>, which makes perfect sense considering both versions of the code still need to do the same transcoding from UTF-8 to UTF-16, but the <strong>StringPool</strong> one also needs to deal with the additional logic to update its internal data structures — despite this the difference is still just 8%. On the other hand, doing the decoding manually with <strong>Utf8.ToUtf16</strong> lets us reduce the overhead and gives us better performance than the original version, even including the extra work needed to manage the pooling. And in both cases, if we look at the memory usage, we can see that using <strong>StringPool</strong> reduced the total allocations from <strong>67 MB</strong> to just <strong>512 B</strong>: this new implementation is using over <strong>100,000x less memory</strong>! If we use the profiler to inspect the allocations, we can verify that this new version is only ever allocating the unique <strong>string</strong> instances one for each label we encountered, and then working with no additional allocations from that point on.</p><h4><strong>How does it work?</strong></h4><p>We can briefly go into some more details on how the <strong>StringPool</strong> type actually works. Here is a diagram that illustrates a simplified representation of the internal architecture being used:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxDWH5RCzz_lhpLUEVhAPw.png" /></figure><p>There are 3 main components that make up the <strong>StringPool</strong> type:</p><ul><li>Each <strong>StringPool</strong> instance contains a number of buckets, that is dynamically calculated upon construction based on the maximum capacity of the pool. Each of these buckets is independent from the others and implements the actual LRU pool logic. The reason for these buckets is to provide a more fine-grained locking ability and reduce thread contention when multiple threads are trying to work on a given <strong>StringPool</strong> instance. Depending on the input sequence of characters being used to index the pool, a target bucket is selected and a lock is taken on just that bucket, so that other threads will be able to still work concurrently on other buckets. This is possible because each unique <strong>ReadOnlySpan&lt;char&gt;</strong> value will only map to a single bucket.</li><li>Each bucket contains a hashset, which is implemented using the standard approach of using hashcode-indexed buckets and chained sequences, but then specifically tine-tuned to work within the <strong>StringPool</strong> type. For instance, each entry also stores the index of the associated min-heap item (this is needed to perform the downheap operation when an existing map instance is accessed), and some operations have also been heavily optimized by leveraging how the <strong>StringPool</strong> type work.</li><li>Each bucket also contains a min-heap, implemented as a 0-indexed array. Each heap entry contains a timestamp, which is incremented every time a <strong>string</strong> instance is retrieved from the pool, and the index of the relative index in the chained list in the map.</li></ul><p>As for the <strong>Memory2D&lt;T&gt;</strong> and <strong>Span2D&lt;T&gt;</strong> types, feel free to have a look at the source code if you’re interested in more details about all this!</p><h3><strong>Memory&lt;T&gt; casting</strong></h3><p>Due to how the <strong>Memory&lt;T&gt;</strong> and <strong>Span&lt;T&gt;</strong> types work, there is no intuitive way to cast a <strong>Memory&lt;TFrom&gt;</strong> instance to a <strong>Memory&lt;TTo&gt;</strong> instance, such that the underlying data would just be reinterpret-cast to type <strong>TTo</strong> when getting a <strong>Span&lt;TTo&gt;</strong> from the second <strong>Memory&lt;T&gt;</strong> instance: there are APIs to to do that for <strong>Span&lt;T&gt;</strong> instances, but not for <strong>Memory&lt;T&gt;</strong>. The reason for that is that with a <strong>Span&lt;T&gt;</strong> it’s just a matter of retrieving the wrapped reference, reinterpreting it and then adjusting the size, then creating a new <strong>Span&lt;T&gt;</strong> instance (there is a built-in API for this in the BCL as well, it’s <a href="https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.memorymarshal.cast"><strong>MemoryMarshal.Cast</strong></a>). But a <strong>Memory&lt;T&gt;</strong> instance is completely different: it wraps an object which could be either a <strong>string</strong>, a <strong>T[]</strong> array or a <a href="https://docs.microsoft.com/dotnet/api/system.buffers.memorymanager-1"><strong>MemoryManager&lt;T&gt;</strong></a> instance and stores a starting offset and length, and then dynamically creates a new <strong>Span&lt;T&gt;</strong> when needed. Because of this, “casting” a <strong>Memory&lt;T&gt;</strong> is not as trivial, and there is no built-in way to do this with the existing APIs.</p><p>I originally had the idea for this feature after seeing <a href="https://github.com/SixLabors/ImageSharp/issues/1097">this issue</a> in the amazing library <a href="https://github.com/SixLabors/ImageSharp"><strong>ImageSharp</strong></a>, and after adding (limited) support for this there I decided to also expand on this feature and make it part of the <strong>HighPerformance</strong> package, given the number of other developers that expressed interest in using this API as well. The usage is extremely straightforward and mirrors how you can use extensions to cast a <strong>Span&lt;T&gt;</strong> instance as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a3cc9e0e23d8637297ac8ce550be011/href">https://medium.com/media/7a3cc9e0e23d8637297ac8ce550be011/href</a></iframe><p>These extensions work by first retrieving the underlying data storage for the input <strong>Memory&lt;T&gt;</strong> instance (so that they can work on it directly for better efficiency), and then creating a custom <strong>MemoryManager&lt;T&gt;</strong> instance that is responsible for creating <strong>Span&lt;T&gt;</strong> instances of the target type when requested. There are three different types of custom memory managers (for <strong>string</strong>, <strong>T[]</strong> arrays or <strong>MemoryManager&lt;T&gt;</strong>), so that the extension can automatically select the right one and reduce overhead (as opposed to having a single one wrapping the entire input <strong>Memory&lt;T&gt;</strong> instance). Additionally, chained casts are optimized in such a way that if you attempt to cast a <strong>Memory&lt;T&gt;</strong> that itself was the result of a previous casting operation, the new cast will first retrieve the original data storage and wrap that one directly. This means that even if you try casting a <strong>Memory&lt;T&gt;</strong> instance multiple times, each resulting <strong>Memory&lt;T&gt;</strong> instance will only be using a single custom <strong>MemoryManager&lt;T&gt;</strong> instance to retrieve data, as opposed to just chaining all the previous instances as well for each cast operation.</p><h3>IBufferWriter&lt;byte&gt;.AsStream() extension</h3><p>This last feature I want to mention combines two different capabilities into one: it enables <a href="https://docs.microsoft.com/dotnet/api/system.buffers.ibufferwriter-1"><strong>IBufferWriter&lt;T&gt;</strong></a> to interoperate with <a href="https://docs.microsoft.com/dotnet/api/system.io.stream"><strong>Stream</strong></a>-based APIs, and indirectly it also offers the ability to implement a memory pooled <a href="https://docs.microsoft.com/dotnet/api/system.io.memorystream"><strong>MemoryStream</strong></a>. The reason why this extension was added is that even in modern codebases going all-in with newer APIs and types such as <strong>Span&lt;T&gt;</strong>, it’s very common to have to deal with possibly older APIs that just accept a <strong>Stream</strong> instance as input: this extension is meant to help in these scenarios by providing an extra bridge between these two worlds.</p><p>As a practical example of where this new API could be used, here is a simple snippet of code that I found in a codebase I was recently browsing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97aeaa6d6c2fd0e0a1298d27e28c1aa2/href">https://medium.com/media/97aeaa6d6c2fd0e0a1298d27e28c1aa2/href</a></iframe><p>This code is simply compressing and decompressing data passed in a <strong>byte[]</strong> array, using the <a href="https://docs.microsoft.com/dotnet/api/system.io.compression.deflatestream"><strong>DeflateStream</strong></a> API. We can see how this code is not particularly efficient for a number of reasons, from the <strong>MemoryStream</strong> type not using array pooling to those final <strong>ToArray()</strong> calls to get the new array to return. Some of these issues could be worked around, such as replacing the <strong>ToArray()</strong> calls with <strong>GetBuffer()</strong>, and changing the return type to a <strong>Memory&lt;byte&gt;</strong> instead, but the end result would still not be ideal. For one, we have no way to transfer ownership of the returned buffer, so we have no way of making it a pooled array. Here is how we could rewrite the two methods above using some of the APIs in the <strong>HighPerformance</strong> package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/124e5b757de29dd29ddaa390e81c9782/href">https://medium.com/media/124e5b757de29dd29ddaa390e81c9782/href</a></iframe><p>We can immediately see a number of differences in this second snippet. The return types have now been changed to <strong>IMemoryOwner&lt;byte&gt;</strong>, so we can transfer ownership and allow consumers to also dispose the buffer so that it can be returned to the pool. This means that we can amortize the memory allocations for repeated calls to this method. Similarly, we’re not using the <strong>ArrayPoolBufferWriter&lt;T&gt;</strong> type instead of <strong>MemoryStream</strong>, and turning it into a <strong>Stream</strong> to pass it to the <a href="https://docs.microsoft.com/dotnet/api/system.io.compression.deflatestream"><strong>DeflateStream</strong></a> APIs using this new <strong>AsStream()</strong> extension. This effectively lets us treat it as a pooled stream, so that as the <strong>DeflateStream</strong> type writes data to it, the internal buffer will just be expanded by renting a new larger array from the shared pool. This again lets us amortize the memory allocations over a larger number of calls. We also tweaked the input types to allow consumers to have more flexibility over the exact data source they use when invoking these two methods.</p><p>And here are some benchmarks to compare these two versions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a2e53379afc92cb44ee4de206632130/href">https://medium.com/media/4a2e53379afc92cb44ee4de206632130/href</a></iframe><p>The pooled version is faster in both cases, especially when decompressing data, and more importantly it uses a fraction of the allocated memory every time! This is just an example of how all these APIs can be used together with the existing types and APIs from the BCL to write faster and more efficient code.</p><h3>There’s more!</h3><p>If you’re interested in learning more about the HighPerformance package, check out the docs in the .NET API browser, or the source code in the Windows Community Toolkit repo on GitHub! The new 7.0 releases many other new features, improvements and bug fixes that I couldn’t fit in a single post, and there’s more things planned for the future still! If you have any feedbacks or ideas, please feel free to open an issue as well!</p><p>Here’s a few useful links:</p><ul><li><a href="https://blogs.windows.com/windowsdeveloper/2021/03/16/announcing-windows-community-toolkit-v7-0/">Windows Community Toolkit 7.0.0 announcement</a></li><li><a href="https://docs.microsoft.com/en-us/dotnet/api/?term=microsoft.toolkit.highperformance">.NET API browser</a></li><li><a href="https://docs.microsoft.com/en-us/windows/communitytoolkit/high-performance/introduction">Windows Community Toolkit docs</a></li></ul><h3>Happy coding! 🚀</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f31079ae2be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enabling and using C# 9 features on older and “unsupported” runtimes]]></title>
            <link>https://sergiopedri.medium.com/enabling-and-using-c-9-features-on-older-and-unsupported-runtimes-ce384d8debb?source=rss-138aedd31ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce384d8debb</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[microsoft]]></category>
            <dc:creator><![CDATA[Sergio Pedri]]></dc:creator>
            <pubDate>Fri, 13 Nov 2020 11:32:02 GMT</pubDate>
            <atom:updated>2020-11-13T11:32:02.401Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cog9iiFl_3wLBn_n6JfvBA.png" /><figcaption>C# language — background image by Procreator UX Design Studio on Unsplash</figcaption></figure><p>With this year’s <a href="https://www.dotnetconf.net/">.NET Conf</a> just coming to a close, we have finally been introduced to the public release of <a href="https://devblogs.microsoft.com/dotnet/announcing-net-5-0/">.NET 5</a> and <a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-9">C# 9</a>, which are now widely available and can be used by developers using at least Visual Studio version 16.8, that comes bundled with all the necessary components to build libraries and applications using these two new technologies.</p><p>Despite all the excitement around all of this, I have seen plenty of developers on Twitter and other channels feeling left out. The reason was they thought they could not benefit from either of these new tools on older frameworks such as UWP, Xamarin, and all other targets that cannot use neither .NET 5 nor any kind of API that requires more than .NET Standard 2.0 support.</p><p>While it is true that if we are working with a framework that cannot just upgrade to .NET 5, we will not be able to enjoy many of the great features that the new version of the runtime and BCL bring to the table, the same is not actually true for C# 9. At least, not for <em>all</em> of C# 9 features. Many of them (most?) can actually be used by every developer regardless of the runtime in use — the only requirement is to have access to a recent version of the Roslyn compiler, such as the one that is included in Visual Studio 16.8!</p><h3>Why does this work? Is it supported?</h3><p>Simplifying things a bit, we can divide the features of each new C# version into two categories: those that require proper <strong>runtime support</strong> to work, and those that are mostly just <strong>syntactic sugar</strong>. Of course, we will not be able to “backport” any of the new features in the first category to older runtimes, as the C# compiler will simply refuse to work in that case. And that makes perfect sense, as we would not be able to run that code anyway. This category includes features such as <a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#default-interface-methods">default interface methods</a> from C# 8 and <a href="https://docs.microsoft.com/dotnet/csharp/language-reference/proposals/csharp-9.0/covariant-returns">covariant return types</a> in C# 9. The second category instead is a bit more interesting: all the C# features that belong here are ones that make things easier for developers (such as the new <a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-9#record-types">record types</a> in C# 9), but that result in IL code (the .NET bytecode language) that can be executed by older runtimes without any issues. After all, these features are more about changing <em>how</em> we end up with a given binary to execute, but for the most part they introduce nothing new at the IL level. Which is great for us — it means we can “backport” them!</p><h3>Level 1: what works right out of the box</h3><p>Let’s start with what we can use as soon as we set the language version in our project to C# 9 — we simply need to add this line in our .csproj file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73f9fdadf0b28f1e82cbbfc14b8f63b9/href">https://medium.com/media/73f9fdadf0b28f1e82cbbfc14b8f63b9/href</a></iframe><p>With this, we will already be able to use all C# 9 features that do not require runtime support or additional types — and there’s quite a few of them!</p><ul><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-9#top-level-statements">Top-level statements</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-9#pattern-matching-enhancements">Pattern matching enhancements</a></li><li>Native sized integers</li><li>Function pointers*</li><li>Target-typed new expressions</li><li>Static anonymous functions</li><li>Target-typed conditional expressions</li><li>Extension <strong>GetEnumerator</strong> in <strong>foreach</strong> loops</li><li>Lambda discard parameters</li><li>Attributes on local functions</li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#readonly-members">Readonly members</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#more-patterns-in-more-places">Improved pattern matching</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#using-declarations">Using declarations</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#static-local-functions">Static local functions</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#null-coalescing-assignment">Null-coalescing assignment</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#unmanaged-constructed-types">Unmanaged constructed types</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#stackalloc-in-nested-expressions">Stackalloc in nested expressions</a></li><li><a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-8#enhancement-of-interpolated-verbatim-strings">Improved interpolated verbatim strings</a></li></ul><p><em>*On some older frameworks such as UWP, function pointers will still be supported (including the ability to specify an explicit calling convention), but the usage of the </em><strong><em>unmanaged</em></strong><em> keyword to declare a function pointer using the default calling convention for the platform in use might not be supported.</em></p><h4>What about nullable reference types?</h4><p>Of course, nullable reference types are a great addition to C# 8, as they make it much easier to avoid all those nasty null reference exceptions. These work just fine, but they are hidden behind a compiler flag that is off by default, so we just need one more line in our .csproj files to enable them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6fd743444ae5c1a48ff99ebb034f871/href">https://medium.com/media/a6fd743444ae5c1a48ff99ebb034f871/href</a></iframe><p>This will enable support for them in .NET Standard libraries and a number of other targets. One small caveat for those of you that work on UWP: in order to use this feature we will also need to manually annotate each of our .cs files, with a specific compiler directive. We just need to add this line at the top of all our files, and we will be able to use the nullable annotations there as well:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4407c38ac8a239dff8f0118e8b6954d/href">https://medium.com/media/e4407c38ac8a239dff8f0118e8b6954d/href</a></iframe><p>While using nullable reference types in our own code will work just fine, along with the static flow analysis powered by Roslyn, we will not benefit from APIs in the BCL being annotated, as most of that work has only been done in .NET 5. Because of this, we will need to be careful to preserve the proper annotations when passing values to and from all of those methods.</p><p>There is one more thing to consider on the topic of nullable reference types: not all attributes are available on .NET Standard 2.0 and other similar runtimes. For that, let’s move to the next section.</p><h3>Level 2: what we can enable support for</h3><p>While we still have some features left in C# 8 and 9 that can work on our older targets, these remaining ones will need some extra care in order to make the Roslyn compiler happy. Specifically, these are features that are backwards compatible, but do need some specific types or attributes to be present in the project. The good news is that if we are missing libraries we can just reference them from NuGet, and if we miss types we can literally just copy them from the <a href="https://github.com/dotnet/runtime">CoreCLR source on GitHub</a> and paste them into our project! The C# compiler does not actually need those types to be built-in — as long as it can find them in the right place, that will be enough for it to successfully build our code. So, let’s go through all the remaining features one by one!</p><h4>C# 9 records and init-only properties</h4><p>The new <a href="https://docs.microsoft.com/dotnet/csharp/whats-new/csharp-9#record-types">record types</a> introduced in C# 9 can greatly reduce the amount of boilerplate code that is required to implement simple models, but they are one of the features that needs some help to work properly on older targets. Specifically, the C# compiler will need the special <strong>IsExternalInit</strong> type to be present in our project. To enable support for this, we can simply copy the following code anywhere in your our and then try building again!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54bdd4da6663a146526ec7e5ef91d4ee/href">https://medium.com/media/54bdd4da6663a146526ec7e5ef91d4ee/href</a></iframe><h4>C# 9 [SkipLocalsInit] attribute</h4><p>This new attribute is useful in performance critical scenarios, and instructs the compiler not to emit the .locals <strong>init</strong> flag for variables in a method. This can avoid unnecessary zero-initializations of variables and improve performance. The attribute is not available on older runtimes, but as with records, we simply need to copy it into our project and then use it normally. Roslyn will recognize it and use it just fine, since it just checks the type name and namespace, and not the assembly the type actually belongs to. Here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b7f458a7631ff31b31ee84c9ad9ba91d/href">https://medium.com/media/b7f458a7631ff31b31ee84c9ad9ba91d/href</a></iframe><h4>C# 8 asynchronous streams and disposables</h4><p>This feature relies on the <a href="https://docs.microsoft.com/dotnet/api/system.collections.generic.iasyncenumerable-1"><strong>IAsyncEnumerable&lt;T&gt;</strong></a> and <a href="https://docs.microsoft.com/dotnet/api/system.iasyncdisposable"><strong>IAsyncDisposable</strong></a> types, and allows us to write asynchronous enumerators, to use the new <strong>await foreach</strong> construct and to implement asynchronous dispose methods to enable the new <strong>await using</strong> syntax. All we need to do in this case is to add a reference to the <a href="https://www.nuget.org/packages/microsoft.bcl.asyncinterfaces/"><strong>Microsoft.Bcl.AsyncInterfaces</strong></a> NuGet package, which includes all these necessary types. Once we have a reference to that package we will be able to use all of those new APIs with no problems at all:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f0c1876ca33ebc6b0530fc0860701f7/href">https://medium.com/media/7f0c1876ca33ebc6b0530fc0860701f7/href</a></iframe><h4>Flow analysis attributes</h4><p>You might have noticed that, especially with respect to nullable reference types, not all the necessary attributes to decorate fields, properties, methods and other members are available, especially when working on .NET Standard 2.0 and below. These are attributes like <strong>[MaybeNullWhen]</strong>,<strong>[NotNullWhen]</strong> and others <a href="https://docs.microsoft.com/dotnet/csharp/language-reference/attributes/nullable-analysis">detailed in the docs</a> that enable better static analysis, as they can give the compiler more information about how our code is interacting with values. Thankfully, we can just backport all of these from the <a href="https://github.com/dotnet/runtime/blob/master/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs">CoreCLR source</a> and then use them just like we would have done if they had already been available in the framework we are working with. Here is a gist with all the currently available attributes ready to use — we can just paste this file into our project and start using them wherever we need:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e62f1af6d1338a2fef62f8afd0d87d97/href">https://medium.com/media/e62f1af6d1338a2fef62f8afd0d87d97/href</a></iframe><p>I know that this is not quite the same as just having full built-in support for C# 9, but if you can live without those few features that cannot be ported to older targets, and if you are fine with the small amount of work needed to manually enable some of the remaining ones, hopefully this post will help you have a more pleasant time while maintaining your apps and libraries.</p><p>Be sure to know that as a UWP developer myself (so being stuck on .NET Standard 2.0 for the time being), I can say that there are plenty of other devs like me that really appreciate the time and effort put into supporting libraries that all of us still on “older” technologies can use.</p><h3>Happy coding! 🚀</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce384d8debb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing string.Count all the way from LINQ to hardware accelerated vectorized instructions]]></title>
            <link>https://sergiopedri.medium.com/optimizing-string-count-all-the-way-from-linq-to-hardware-accelerated-vectorized-instructions-186816010ad9?source=rss-138aedd31ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/186816010ad9</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[simd]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[vectorization]]></category>
            <dc:creator><![CDATA[Sergio Pedri]]></dc:creator>
            <pubDate>Thu, 09 Jan 2020 10:44:19 GMT</pubDate>
            <atom:updated>2020-01-09T10:44:19.167Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AeOmNaYA1IURQ1mPcWdmWA.png" /><figcaption>C# language — background image by Sai Kiran Anagani on Unsplash</figcaption></figure><p>I have always been very interested in code optimizations, even when achieving the best possible execution time is not really necessary — I consider trying to improve my code and squeezing out as much performance as possible to be both fun and a useful learning exercise.</p><p>I have recently rewritten a simple method to count the number of occurrences of a given <strong>char</strong> into a <strong>string</strong>, and in doing so I also had a chance to experiment with vectorized instructions, which is something that I had always considered fascinating but that I had never taken the time to read up on well enough to actually use them in my own code.</p><p>This blog post is a brief introduction to the world of vectorized instructions in C#, and it is meant to be accessible for developers that have never really used them before on their own, just like I had not until today. The code that is included in this post is by no means anything extremely advanced — I’m just sharing the steps I personally took in optimizing this specific algorithm, and what I learnt along the way.</p><blockquote>If you happen to have never spent much time optimizing code, I hope this post will make you even a tiny bit more interested in this topic!</blockquote><h3>LINQ to the rescue</h3><p>The first implementation that everyone will probably come up with when implementing a similar algorithm (myself included) uses the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.count?view=netcore-3.1#System_Linq_Enumerable_Count__1_System_Collections_Generic_IEnumerable___0__System_Func___0_System_Boolean__"><strong>Count&lt;T&gt;(IEnumerable&lt;T&gt;, Func&lt;T, bool&gt;)</strong></a> API from the <strong>System.Linq</strong> namespace. This API is very helpful as it provides an easy way to solve this problem, which is extremely compact to write and still reasonably fast. We just need to invoke this method with a function that checks each character in our <strong>string</strong> against the one we are looking for:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd3378b05c5763bf2918d0be94905f4f/href">https://medium.com/media/bd3378b05c5763bf2918d0be94905f4f/href</a></iframe><p>This works just fine and has the big advantage of being virtually impossible to get wrong — once this method is implemented you likely will never find a bug coming from this piece of code, which is certainly a plus when working with larger projects. But, there are two major drawbacks:</p><ul><li><strong>Memory allocation</strong>: the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.func-2?view=netcore-3.1"><strong>Func&lt;T, TResult&gt;</strong></a> instance we’re using in this method is generating a closure, since it’s capturing our parameter <strong>char c</strong> from the caller method. If you’re not familiar with closures, you can read up more on them in my other blog post, <a href="https://medium.com/@SergioPedri/optimizing-reflection-with-dynamic-code-generation-6e15cef4b1a2">here</a>. Suffice to say, it involves the runtime allocating an <strong>object</strong> every time we use this method, which causes unnecessary memory usage and <a href="https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/fundamentals">GC pressure</a>. Additionally, we’re also allocating memory for the <strong>string</strong> iterator that the LINQ method is working on.</li><li><strong>Slow execution</strong>: the LINQ method we’re using goes over all the characters through the iterator, which is much slower than doing the same with a traditional <strong>for</strong> loop. In this case we’re also invoking our <strong>Func&lt;T, TResult&gt;</strong> delegate for each individual character, which again has a higher overhead compared to simply comparing each character directly.</li></ul><h3>Return to the past</h3><p>Let’s leave the user friendly land of functional programming and go back to a classic, imperative style implementation of our algorithm:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbda20992b0d46723e1bc7ad18cbaa90/href">https://medium.com/media/cbda20992b0d46723e1bc7ad18cbaa90/href</a></iframe><p>First, there is an interesting optimization that the C# compiler is doing for us: the <strong>string</strong> type (together with <strong>T[]</strong> arrays) is treated in a special way when used in a <strong>foreach</strong> loop, and results in that code being transformed into a classic <strong>for</strong> loop. This has the advantage of being easier to write for us, since we don’t have to deal with manual indexing of characters in the <strong>string</strong>, while still having exactly the same performance as a classic loop. Plus, since the compiler knows we are iterating exactly within the bounds of the input <strong>string</strong>, it will emit a nicely optimized assembly code with no unnecessary <a href="https://en.wikipedia.org/wiki/Bounds_checking">bounds checks</a>. This implementation is much faster than the LINQ version, and with it the memory allocation problem has already been solved entirely.</p><h3>Full steam ahead</h3><p>The previous implementation has one bottleneck: each loop iteration has one <a href="https://en.wikipedia.org/wiki/Branch_(computer_science)">conditional branch</a>, specifically that <strong>if</strong> statement on line 7. Branches should always be kept at a minimum in high performance code, and for a more in-depth explanation of the rationale behind this I highly suggest reading up this <a href="https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array">StackOverflow question and answer</a>. To sum it up, the CPU will try to anticipate what the result of a branch instruction will be, and every time it gets it wrong there will be a relatively high performance penalty. Luckily, in this case we can just completely remove that branch by leveraging how <strong>bool</strong> variables are stored in memory during execution.</p><p><em>From this point on, the snippets will make use of </em><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref"><strong><em>ref</em></strong></a><em> variables and methods from the </em><a href="https://mattwarren.org/2016/09/14/Subverting-.NET-Type-Safety-with-System.Runtime.CompilerServices.Unsafe/"><strong><em>Unsafe</em></strong></a><em> and </em><a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.memorymarshal?view=netcore-3.1"><strong><em>MemoryMarshal</em></strong></a><em> class. I have added detailed comments over every single line to make it easy to follow, but if you want to go more in depth on this feel free to read up </em><a href="https://medium.com/@SergioPedri/optimizing-reflection-with-dynamic-code-generation-6e15cef4b1a2"><em>my previous blog post</em></a><em> or the official MS docs.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d37f68661793578361d9f0c649ef03d/href">https://medium.com/media/0d37f68661793578361d9f0c649ef03d/href</a></iframe><p>This is another welcome improvement, but we are not quite there yet. This is about as fast as we can get without delving into more advanced techniques. And it is now time to do just that, by adding vectorization.</p><p><em>Some of you might correctly point out that this latest implementation might still be improved by adding </em><a href="https://en.wikipedia.org/wiki/Loop_unrolling"><em>loop unrolling</em></a><em>. That is certainly true, but for the purposes of this post we will leave that part out.</em></p><h3>What are vectorized instructions anyway?</h3><p>Vectorized instructions, often called <a href="https://en.wikipedia.org/wiki/SIMD"><strong>SIMD instructions</strong></a> (single instruction multiple data) are instructions that leverage special registers in modern CPUs to speedup certain types of operations. These registers can hold a series of values next to each other, so that a single operation can be executed on all of them at the same time.</p><p>One important thing to note is that the size of a SIMD register depends on the specific processor, and that it also influences the number of values it can hold at any time. To be precise, there are different SIMD instructions that work on different SIMD registers, each of a specific size, but the C# APIs we will use provide a nice abstraction over this and expose these registers to us as a vector type that can vary in size depending on the specific device we are executing our code on. For instance, it we have 128 bits registers at our disposal, we will be able to store either 2 <strong>double</strong> values (64 bits each), or 4 <strong>int</strong> or <strong>float</strong> values (32 bits each), 8 <strong>ushort</strong> or <strong>short</strong> values (16 bits each) or 16 <strong>byte</strong> or <strong>sbyte</strong> values (8 bits each). SIMD registers might also not be available at all, so we should always manually check whether that’s the case before executing our vectorized code.</p><p>Suppose we had two <strong>int[]</strong> arrays and we wanted to write to another <strong>int[]</strong> array of the same size the sum of each pair of values. Instead of going through each element one by one, we could load a chunk of consecutive values from each array into two separate SIMD registers, sum those registers together in a single instruction, and then copy that resulting register to the right location into the <strong>int[]</strong> array to return from the method. The type we need is <a href="https://docs.microsoft.com/en-us/dotnet/api/system.numerics.vector-1?view=netcore-3.1"><strong>Vector&lt;T&gt;</strong></a>, which represents a SIMD register with elements of a given type. Here is a sample with both the traditional implementation of this algorithm using a <strong>for</strong> loop, and one using the <strong>Vector</strong> and <strong>Vector&lt;T&gt;</strong> APIs:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/807b9ad754c93a70ec5ad0da02a86432/href">https://medium.com/media/807b9ad754c93a70ec5ad0da02a86432/href</a></iframe><p>With this proof of concept, we can now move on to an implementation of our original <strong>Count</strong> method that leverages the power of SIMD instructions.</p><h3>SIMD FTW</h3><p>Back to our original problem, there is a small complication: the <strong>Vector&lt;T&gt;</strong> type does not have an API that just counts the number of occurrences of a value in a SIMD register — we will have to implement this ourselves. Luckily, this only requires a couple of bit operations on top of the basic SIMD structure we have used in our previous <strong>SumSimd</strong> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e56b754b2cf9218756951da619a862f3/href">https://medium.com/media/e56b754b2cf9218756951da619a862f3/href</a></iframe><h3>Was it worth it?</h3><p>Here are the results when running the 4 different <strong>Count</strong> implementations on a sample text (a 200 lines document with the code for the 4 <strong>Count</strong> versions described above) and looking for the <strong>‘\n’</strong> character. Each implementation has been executed in a loop with <strong>N</strong> iterations each time, to minimize variations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f795d26c0a2df7bf04e5258614e5ed/href">https://medium.com/media/40f795d26c0a2df7bf04e5258614e5ed/href</a></iframe><p>We can see that the SIMD-powered <strong>Count</strong> implementation is <strong>110x</strong> faster than the LINQ version, and <strong>13x</strong> faster than the <strong>foreach</strong> version. Additionally, we can see that both the <strong>foreach</strong> and SIMD versions use no memory at all, whereas the LINQ version allocates 120 bytes of memory for each individual invocation.</p><p>Whether or not these improvements are worth the time and effort is entirely up to you (especially since even the LINQ version is still only taking a few microseconds to run), but the speedup is indeed noticeable at least on paper, and doing all of this was definitely a fun experiment!</p><p>As with my previous blog post, I have added links to every single API that I have used across all the code snippets, if you want to read up more about them. I hope you enjoyed reading this post, please let me know if you spot any mistakes in any of the method implementations!</p><h3>Happy coding! 🚀</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=186816010ad9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimizing reflection in C# via dynamic code generation]]></title>
            <link>https://sergiopedri.medium.com/optimizing-reflection-with-dynamic-code-generation-6e15cef4b1a2?source=rss-138aedd31ff7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e15cef4b1a2</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Sergio Pedri]]></dc:creator>
            <pubDate>Tue, 24 Sep 2019 18:36:53 GMT</pubDate>
            <atom:updated>2019-09-26T10:14:59.664Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qUhbvoCfw6Gvrmg0V7_tuQ.png" /><figcaption>C# language — background by Fotis Fotopolous on Unsplash</figcaption></figure><p>I have recently been spending a lot of time working on <a href="https://github.com/Sergio0694/ComputeSharp"><strong>ComputeSharp</strong></a>, a .NET Standard 2.1 library written in C# 8.0 that lets you run code in parallel on the GPU through DX12 and dynamically generated HLSL compute shaders. That is a somewhat unintuitive description for a library that does something conceptually simple: it runs code in parallel in a manner similar to <a href="https://docs.microsoft.com/dotnet/api/system.threading.tasks.parallel.for"><strong>Parallel.For</strong></a>, but on the GPU instead of on the CPU.</p><p>The library works as follows: just like <strong>Parallel.For</strong> it takes an <a href="https://docs.microsoft.com/dotnet/api/system.action-1"><strong>Action&lt;T&gt;</strong></a> instance representing the code you want to run on the GPU, it then decompiles it to generate the shader code to be compiled and executed on the GPU, and inspects it to identify all the variables that the code is accessing. Once these values have been discovered, they need to be properly loaded so that the GPU can access them and the shader can finally be executed.</p><p>This post is a case study into some of the technical challenges I faced when writing the code that handles the variables extraction and loading, and how I managed to get a <strong>&gt;20x </strong>performance improvement when moving from reflection to dynamic code generation. It is not meant to be a tutorial to follow step by step, but more of a summary of how I approached this problem and eventually solved it. I have learnt a lot while working on this library, and here I just want to share some of that knowledge and hopefully give new ideas to other developers working on their personal projects. After all, I got the idea to use dynamic code generation while going through <a href="https://www.reddit.com/r/csharp/comments/d49mxr/i_started_a_youtube_channel_for_advanced_c_coding/">this Reddit post</a>, and I would really like people reading this post to find the same inspiration I had to start learning about some new topic I had never really explored before.</p><p>I will start by introducing the issue at hand, and I will generalize it so that we will not need to care about the specifics of my library or its codebase. I will also be describing all the necessary details about how the C# compiler works and what it does behind the scenes, so that every C# developer will be able to understand what is going on at any time, even without previous experience in this particular area.</p><blockquote>If you have never dealt with reflection or dynamic code generation before, welcome to the magical world of metaprogramming!</blockquote><h3>The goal we are trying to achieve</h3><p>We want to write a method that given a <a href="https://docs.microsoft.com/dotnet/csharp/programming-guide/delegates/using-delegates"><strong>Delegate</strong></a> instance with an associated closure retrieves the values of all the variables that are captured by that closure. Additionally, we want all those values to be loaded and stored in two different arrays: an <strong>object[]</strong> array for reference types and a <strong>byte[]</strong> array for value types. We will serialize all value types assuming that they respect the <a href="https://docs.microsoft.com/dotnet/csharp/language-reference/proposals/csharp-7.3/blittable"><strong>unmanaged</strong></a> constraint.</p><h3>C# closures</h3><p>Let’s consider the following code snippet with a practical example of a delegate, to introduce the concept of closures in the C# language:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/38b05c160a8a9e149aae74e74b1afae8/href">https://medium.com/media/38b05c160a8a9e149aae74e74b1afae8/href</a></iframe><p>The <strong>Delegate</strong> we defined (an <strong>Action&lt;int&gt;</strong> instance in this case) is accessing the variables “array” and “value” from its parent method. To make this possible the C# compiler creates a closure, which to use <a href="https://stackoverflow.com/questions/428617/what-are-closures-in-net">Jon Skeet’s words</a> can be described as the following:</p><blockquote>[…] a block of code which can be executed at a later time, but which maintains the environment in which it was first created — i.e. it can still use the local variables of the method which created it, even after that method has finished executing.</blockquote><p>We can look at the code the C# compiler generates when compiling the previous code snippet to see how this is achieved:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/648be1a22a388f00b6ad57d2a0dd7b7b/href">https://medium.com/media/648be1a22a388f00b6ad57d2a0dd7b7b/href</a></iframe><p>The compiler has created a closure class, which in this case is <strong>&lt;&gt;c__DisplayClass0_0</strong>. The class name is not valid according to the C# syntax (as it starts with an angle bracket), but the compiler is actually quite happy with it anyway. This is particularly useful to avoid having to worry about potential name collisions with user-defined types. This class exposes two fields representing our two captured variables, and a method which corresponds to the one we specified when declaring the <strong>Delegate</strong> instance. We can see that our code has been replaced by an instantiation of the closure class, and that our two variables have been assigned to the two fields in that class, which is how they can still be used even after the method has returned.</p><p><em>Note that if our lambda expression had not actually captured any variables, the resulting closure class would have had a slightly different structure. We are not going to take that scenario into account and just assume that there will always be at least one captured variable.</em></p><p>The previous structure becomes slightly more complicated if we capture variables that are declared in different scopes, like in this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca52bc7738fb523083c3bc0a99e07a36/href">https://medium.com/media/ca52bc7738fb523083c3bc0a99e07a36/href</a></iframe><p>Here we have created a new scope using a pair of brackets with no additional logic tied to them, but the same would have happened if we had used a <strong>for</strong> loop, a <a href="https://docs.microsoft.com/dotnet/csharp/language-reference/keywords/using-statement"><strong>using statement</strong></a> or any other scoped constructs. Let’s take a look at the generated closure in this case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dc02ac23af4405bcb8eb33252869d21/href">https://medium.com/media/4dc02ac23af4405bcb8eb33252869d21/href</a></iframe><p>There’s two of them now! The compiler has created a separate closure class for each scope that the captured variables belong to, going from the innermost to the outermost one. The closure class that hosts the method representing our lambda expression has a field named <strong>CS$&lt;&gt;8__locals1</strong>, which does not correspond to any of our captured variables: that is a reference to the instance of the other closure class containing the captured variable from the outer scope. This will happen for any additional scope, which means that we will need our code to handle any number of nested closure classes.</p><h3>Introducing reflection</h3><p>The first approach to solve this problem simply consists in using reflection, both to inspect the closure class (or classes) to identify the fields we are interested in, and to extract the values of those fields when needed. To introduce the topic to those that have never used reflection before, here is a small example that shows how we can use reflection to retrieve the value of a given property of an instance of a given type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b464b03588b4aa993c9165fb8d4d558/href">https://medium.com/media/1b464b03588b4aa993c9165fb8d4d558/href</a></iframe><p>Let’s imagine that we did not know the type of our <strong>object</strong> variable (which in this case is a <strong>string</strong>), but we did know for sure that it had a property called “Length”. Here we are retrieving the <strong>Type</strong> of that <strong>object</strong> and then a <a href="https://docs.microsoft.com/dotnet/api/system.reflection.propertyinfo"><strong>PropertyInfo</strong></a> instance for the property we need. From there we can get the value of that property for the instance of our <strong>object</strong> by calling <a href="https://docs.microsoft.com/dotnet/api/system.reflection.propertyinfo.getvalue"><strong>GetValue(object)</strong></a>. This method returns the value of a property as an <strong>object</strong>, which in this example we are just displaying on the console.</p><p>In our scenario we will not know in advance the names of the fields in a given closure class, so we will need to retrieve them at runtime, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52f599eb8fd5010af01428212d6fa6a9/href">https://medium.com/media/52f599eb8fd5010af01428212d6fa6a9/href</a></iframe><p>Here we are retrieving a list of all public fields of the type of our <strong>object</strong> using the <a href="https://docs.microsoft.com/dotnet/api/system.type.getfields"><strong>GetFields()</strong></a> method, which returns an array of <a href="https://docs.microsoft.com/dotnet/api/system.reflection.fieldinfo"><strong>FieldInfo</strong></a> items. Then we are just iterating over that array to display the name and value of each field.</p><p>The key concept from these examples is that retrieving the values of all the fields (or properties) of an instance of a given type requires two separate steps: we first have to obtain the <strong>FieldInfo</strong> collection for the type of our object, and then get the value that those fields have for our object instance.</p><h3>Let’s give it a go</h3><p>We can now write a first version of our method to extract the captured variables for a given <strong>Delegate</strong>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1190fe44d32b002e25943e620e810105/href">https://medium.com/media/1190fe44d32b002e25943e620e810105/href</a></iframe><p>Here we are doing the classic <a href="https://en.wikipedia.org/wiki/Tree_traversal">pre-order</a> exploration of our class hierarchy in the input closure: we simply check whether a field name starts with “CS$&lt;&gt;”, which is how the C# compiler marks generated fields for nested closure classes, then if that is the case we recurse and explore that tree, otherwise we simply yield the current field. Note how the <strong>Delegate</strong> class exposes a handy <a href="https://docs.microsoft.com/dotnet/api/system.delegate.target"><strong>Target</strong></a> property that gives us a reference to the instance of the closure type that the delegate will be invoked upon. Let’s test this to see if everything works as expected:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2c781c07cf0e6136af0e03d32272b81/href">https://medium.com/media/f2c781c07cf0e6136af0e03d32272b81/href</a></iframe><p>Everything seems fine, but there is a catch: this code will throw an <a href="https://docs.microsoft.com/dotnet/api/system.argumentexception"><strong>ArgumentException</strong></a> if our closure class contains a nested closure. That is because when we call <a href="https://docs.microsoft.com/dotnet/api/system.reflection.fieldinfo.getvalue"><strong>field.GetValue(action.Target)</strong></a> we are actually passing a reference to the instance of the outermost closure type. But if the field belongs to one of the nested instances, that call will fail because the instance we are using is not the one exposing the field we are trying to get the value for. We can fix this by keeping track of the parents of each field. We will also add a <strong>ClosureField</strong> class to make our updated code a bit cleaner:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6273d34a0758999dd1462595b359b1f9/href">https://medium.com/media/6273d34a0758999dd1462595b359b1f9/href</a></iframe><p>With this change we can now retrieve the values of all fields, both nested and not, and we can test that by running the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8f42e3db16c1dfae7f3733a5b04c78f/href">https://medium.com/media/b8f42e3db16c1dfae7f3733a5b04c78f/href</a></iframe><p>The final step is to write a method that takes as input a <strong>Delegate</strong> and the result of our initial exploration (the list of fields and their relative parents), and produces the two arrays we are interested in. This is how such a method could be structured:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b7a5da8ac684e39d8f3a085bd8878e4/href">https://medium.com/media/3b7a5da8ac684e39d8f3a085bd8878e4/href</a></iframe><p>This might seem complicated for those not familiar with unsafe code, references and pointers, so let’s go over this snippet step by step.</p><ul><li>First we are iterating over the captured fields to calculate the length of the arrays we will need to populate. To get the size in bytes of a captured value type, we can use the <a href="https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.marshal.sizeof"><strong>Marshal.SizeOf(Type)</strong></a> method.</li><li>We then allocate the two arrays, and to keep track of our position in each one of them we initialize two running offsets. The arrays are allocated using the <a href="https://docs.microsoft.com/dotnet/api/system.buffers.arraypool-1"><strong>ArrayPool&lt;T&gt;</strong></a> class, which provides a high-performance pool of arrays of a given type. This means that instead of allocating a new array each time with <strong>new T[int]</strong>, the pool will internally reuse arrays whenever possible, which saves us some time. One thing to note is that when renting arrays through this class, they are not guaranteed to be of the exact size we requested: they could also be bigger. In this snippet we are just returning those arrays to the caller ignoring this implementation detail, just to keep the code more compact.</li><li>Then we iterate over each captured field. If it is not a value type we can just assign it to the right position in the first array. If it is, we need some additional work. <strong>FieldInfo.GetValue(object)</strong> returns the value of a field as an <strong>object</strong>, which means that if the field type is a value type (eg. an <strong>int</strong>), it gets boxed: the runtime will copy it on the heap and pass it around by reference. We are interested in the actual value of that field, not in a reference to it, so we need a way to access that value from here. To do that, we first allocate a <a href="https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.gchandle"><strong>GCHandle</strong></a>. We also tell the runtime to “pin” that object, so we avoid the risk of the garbage collector moving it to another memory location while we are reading from it. Once we have our handle, we can use <a href="https://docs.microsoft.com/dotnet/api/system.runtime.interopservices.gchandle.addrofpinnedobject"><strong>AddrOfPinnedObject()</strong></a> to get the address where the data we need is stored in. Now we need two <strong>ref </strong>pointers to the pinned data and to the target position inside our array: we use <a href="https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.unsafe.asref"><strong>Unsafe.AsRef&lt;T&gt;(void*)</strong></a> to convert the address of the pinned object to a <strong>ref</strong> value, and <a href="https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.unsafe.add"><strong>Unsafe.Add&lt;T&gt;(ref T, int)</strong></a> to shift the <strong>ref</strong> pointer into our <strong>byte[]</strong> array to the right position. Finally, we use <a href="https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.unsafe.copyblock"><strong>Unsafe.CopyBlock&lt;T&gt;(ref T, ref T, uint)</strong></a> to copy the data from one location to the other.</li></ul><h3>First steps with IL</h3><p>If you are not skipping this paragraph, you might have never heard of the word “IL” before. Here is a brief summary of everything you need to know to be able to follow along in the rest of this post:</p><ul><li>IL stands for Intermediate Language, and it is the low-level common language that all the languages running on a .NET runtime (eg. .NET Core) are compiled to. Whenever you compile some C# code, the compiler generates IL code, which is not machine code. When you then run that code, the JIT (Just In Time) compiler is responsible for converting that IL code into machine code in the most efficient way possible.</li><li>Each IL method is made up of a series of opcodes, representing the operations to be executed. These instructions are executed one after the other, with the possibility of jumping to other parts of the codebase when needed. The runtime works by pushing and popping values to its execution stack, which is also used to pass arguments to functions and other instructions. Each opcode can perform one or more operations, like popping values from the stack to read them and pushing new values to the stack so that they can be used when executing other instructions.</li><li>An IL method can also declare a number of local variables, which are accessed by their position (the order in which they are declared).</li><li>When a method returns, the return value is just the value that is at the top of the execution stack in that moment</li></ul><p>Here is an example with a method in C# and its literal translation in IL:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6d1268c9a6cca65836abae8c100a574/href">https://medium.com/media/c6d1268c9a6cca65836abae8c100a574/href</a></iframe><h3>Enter code generation</h3><p>The previous implementation works fine, but using reflection to get the value of all the closure fields is not ideal, as it is generally slow. It would be nice if each captured field exposed a method that took an <strong>object</strong>, cast it to the right type, loaded the field value and returned it. Just like the <strong>FieldInfo.GetValue()</strong> method, but without the slowdown caused by reflection. That is not the case, but we can actually generate these methods ourselves at runtime, through the use of the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.dynamicmethod"><strong>DynamicMethod</strong></a> class and its available APIs.</p><p>This is what such a method should do if we were trying to load and return the value of the <strong>X</strong> field of a boxed <a href="https://docs.microsoft.com/dotnet/api/system.numerics.vector2"><strong>Vector2</strong></a> instance:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1920640cbc3611e52e6c918d72479882/href">https://medium.com/media/1920640cbc3611e52e6c918d72479882/href</a></iframe><p>This IL method first loads the boxed <strong>object</strong> with the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.ldarg_0"><strong>ldarg.0</strong></a> instruction, which simply loads the method argument at position 0, then uses the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.unbox"><strong>unbox</strong></a> instruction to replace that reference in the stack with the unboxed <strong>Vector2</strong> value. Then <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.ldfld"><strong>ldfld</strong></a> reads the value of the specified field (in this case, <strong>Vector2.X</strong>) and <strong>box</strong>, of course, boxes that value before returning.</p><p>To optimize our previous code, let’s write a method that given a <strong>ClosureField</strong> instance builds a dynamic method that loads that field, given an instance of the class that exposes it. In our case, the method will be wrapped by a <a href="https://docs.microsoft.com/dotnet/api/system.func-2"><strong>Func&lt;object, object&gt;</strong></a> instance, as it matches the signature we need:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9326b5d880d10b8907402a1967600ec/href">https://medium.com/media/c9326b5d880d10b8907402a1967600ec/href</a></iframe><p>Once we have this, we just need to store our <strong>ClosureField</strong> instances paired with the relative function to retrieve their values, and use these functions instead of <strong>FieldInfo.GetValue(object)</strong>.</p><p><em>Some of you might correctly point out that such a method could also have been created using </em><a href="https://docs.microsoft.com/dotnet/csharp/programming-guide/concepts/expression-trees/"><em>expression trees</em></a><em>, and that is absolutely right. But, introducing IL was a necessary step to gradually build to our last optimization in the final paragraphs, which wouldn’t have been possible without it.</em></p><h3>Can we do better?</h3><p>Sure! Using these dynamic methods already improves the performance a bit, but we have a slowdown whenever our closure class contains nested fields, as in that case we have to perform additional iterations to access them. We can modify our method to build the dynamic field getters so that it also performs loop unrolling for all the parent fields, when needed. These new dynamic getters will always just take our first target <strong>object</strong> instance and traverse down the fields hierarchy until they reach the desired field. Here is what our method builder looks like now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec009e2da70abb06c99f8e1b27e450e0/href">https://medium.com/media/ec009e2da70abb06c99f8e1b27e450e0/href</a></iframe><p>With this change, we will be able to always get the value of a captured field with a single method invocation to our custom methods, no matter the actual depth of the field in the closure type it belongs to.</p><h3>That’s fine, but can we do even better?</h3><p>If we don not want to accept any compromises, there is definitely room for more optimizations. Let’s look at the possible bottlenecks in our code:</p><ul><li>Multiple invocations, one for each variable getter.</li><li>Boxing: if a getter is retrieving the value of a field of a value type, right now it is also boxing it, as the return type for our functions is <strong>object</strong>.</li><li>Pinning: allocating <strong>GCHandle</strong> instances is expensive, and pinning objects should generally be avoided, if possible.</li><li>Repeated calculations: our <strong>GetData</strong> method is doing a number of operations every time it is invoked, like iterating over the list of captured fields, checking each field to see if it is a value type, calculating the right byte offset to write the value type fields into the <strong>byte</strong> array, etc.</li></ul><p>What we want is a single method that takes our <strong>object</strong> instance and retrieves the values of all the captured fields one after the other. We can do this just like we did the loop unrolling to traverse the hierarchy of each captured field. To solve the issue of value types being boxed, we can avoid returning the values of our captured fields entirely: we can instead generate a method that takes our <strong>object</strong> and <strong>byte</strong> arrays and writes the field values directly from there. We will actually go one step further, and have our method take <strong>ref</strong> parameters to the start of our arrays. This way we will be able to assign values directly to each memory address without the JIT compiler adding safety bound checks, which it does whenever we use the <strong>T[int]</strong> indexer for array types.</p><p>We will first need to write a few extension methods for the <strong>ILGenerator</strong> class, so that the IL generation for this dynamic method will be easier to manage. We are going to perform a much higher number of operations in IL this time around, so we will definitely need them.</p><p>Let’s write a method to store a local value. As mentioned above, local variables in IL are accessed by their index. The instruction we need is <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.stloc"><strong>stloc</strong></a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a235bec9f012fc8eba70ede88a37880/href">https://medium.com/media/9a235bec9f012fc8eba70ede88a37880/href</a></iframe><p>Here we first note one peculiar feature of some IL instructions: in some cases we have at our disposal “multiple versions” of a given opcode that we can use to perform some operations faster. For instance, the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.stloc_0"><strong>stloc.0</strong></a> opcode stores the value on top of the execution stack on the local variable with index 0, and it is faster than the standard <strong>stloc</strong> variant as it does not need to also load the target index as a parameter: it is embedded into the instruction itself. This method makes sure to always use the fastest opcode for the index we need. We also need an <strong>EmitLoadLocal</strong> method, which will be structured just like this one, with the only difference being the fact that it will use the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.ldloc"><strong>ldloc</strong></a> opcode and its variants instead of <strong>stloc</strong>.</p><p>We then need an extension to replace <strong>Unsafe.Add&lt;T&gt;(ref T, int)</strong> calls. Our delegate is receiving a pair of <strong>ref</strong> parameters pointing to the first element in each array, and we want to be able to move those references ahead by a given offset to access other elements of those arrays.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/148e5292b37442e166efb46858964b13/href">https://medium.com/media/148e5292b37442e166efb46858964b13/href</a></iframe><p>Here we are first using the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.ldc_i4"><strong>ldc.i4</strong></a> instruction, which pushes an <strong>int</strong> value to the top of the stack. As before, we are also making sure to always use the fastest possible opcodes, which means using the explicit versions <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.ldc_i4_0"><strong>ldc.i4.0</strong></a> through <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.ldc_i4_8"><strong>ldc.i4.8</strong></a> for values in the [0,8] range, and the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.ldc_i4_s"><strong>ldc.i4.s</strong></a> opcode for values that fit in a <strong>sbyte</strong> parameter. Then, we use <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.conv_i"><strong>conv.i</strong></a> to convert our loaded offset (which is of type <strong>int</strong>) to a <strong>native int</strong>, which is a type that simply represents a memory address, and whose size depends on the CPU architecture the code is running upon. Now we can use <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.add"><strong>add</strong></a>, and we end up with our shifted reference on the top of the execution stack.</p><p>The last piece of the puzzle is a method to write a value at the location pointed by a given reference. This method will assume that the execution stack will have a reference and then a value of a specified type at the top of the execution stack, and will make sure to write the value to the target location using the appropriate instruction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46769938be2ffaa88bec966d43781cd3/href">https://medium.com/media/46769938be2ffaa88bec966d43781cd3/href</a></iframe><p>In this method, we first need to check whether the value we are trying to set is a value type. If it is not, then we just need the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.stind_ref"><strong>stind.ref</strong></a> opcode, which simply stores an <strong>object</strong> reference at a given memory location. If it is, we need to check whether a dedicated opcode is available for our current data type: <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.stind_i4"><strong>stind.i4</strong></a> for <strong>int</strong> values, <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.stind_r4"><strong>stind.r4</strong></a> for <strong>float</strong> values, etc. If that is not the case, we can fallback to the <a href="https://docs.microsoft.com/dotnet/api/system.reflection.emit.opcodes.stobj"><strong>stobj</strong></a> opcode, which despite its confusing name is actually used to copy value types to a supplied memory address. Lastly, we need to check whether the selected opcode is <strong>stobj</strong>, in which case we will also need to pass a type token to indicate the value of the type being assigned, otherwise the runtime will not be able to properly execute that particular instruction.</p><p>We now have all the building blocks we need, and we just need to put them together. We also need to define a custom <strong>delegate</strong> that will wrap our dynamic methods, to be able to specify two of the input parameters as <strong>ref</strong> parameters, and then we can finally build our updated IL method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5247f6c94a6090e2e55c892bfd729ff/href">https://medium.com/media/e5247f6c94a6090e2e55c892bfd729ff/href</a></iframe><p>As before, the first step is creating a <strong>DynamicMethod</strong>, making sure to properly specify its signature, including <strong>ref</strong> parameters. After that, we need to create a mapping for the root closure type and all the nested closure types, so that we can assign a unique index to each of them, which will correspond to their location in our list of local variables in IL. Then we use an <a href="https://docs.microsoft.com/dotnet/api/system.collections.generic.hashset-1"><strong>HashSet&lt;T&gt;</strong></a> to keep track of the indices of the local variables that have already been initialized. Once we have our mappings, we define a local method that we will need to load a given field. This method will check whether the parent instance of that field has already been loaded, and if it is not, it will go back to the most in depth loaded instance and will resume the traversal from there, until the needed instance is assigned to its corresponding local variable and loaded on the execution stack.</p><p>We start the construction of the IL method by declaring all the local variables we need, and then we load the input <strong>object</strong> instance, cast it to the right type and store it in the first local variable. After that, we can iterate over the captured fields, and prepare the target memory reference to write to. If the field is a value type, we load our <strong>ref</strong> <strong>byte</strong> parameter and shift it ahead by the current offset we are at in the <strong>byte[]</strong> array, and then we update it by retrieving the size of the field type. If it is a reference type, we instead load the <strong>ref object</strong> parameter. To update the offset into the <strong>object[]</strong> array, we are using the size of the <strong>object</strong> type, which we can retrieve with the <a href="https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.unsafe.sizeof"><strong>Unsafe.SizeOf&lt;T&gt;()</strong></a> method. This works for every other reference type as well: a memory address has a fixed size that only depends on the CPU architecture. Once this is done, we can call our <strong>LoadField(ClosureField)</strong> method defined above and our extension to write the loaded field value to the target memory location.</p><p>We are almost done now, we just need to change our <strong>GetData(Delegate)</strong> method so that it can use the <strong>delegate</strong> we’ve just created:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d900c90f6b426a315d86934c50cf9d86/href">https://medium.com/media/d900c90f6b426a315d86934c50cf9d86/href</a></iframe><p>The first thing you might notice here is that our method is also taking the number of captured reference and value type variables as parameters, instead of calculating them. This is another optimization we can add, since those values only need to be calculated once instead of every time we want to extract data from a given closure instance. We can apply this same optimization to the previous variants as well, to prevent this version from having an unfair advantage over the others. Looking at the rest of the method body, we are creating our <strong>object[]</strong> and <strong>byte[]</strong> arrays as usual, and then getting references to the first item of each array. If either of the arrays is empty, we do not access it and just use a null reference instead, obtained with <a href="https://docs.microsoft.com/dotnet/api/system.runtime.compilerservices.unsafe.asref"><strong>Unsafe.AsRef&lt;T&gt;(null)</strong></a>. Then we call our latest dynamic IL method, which will take care of all the rest.</p><p>And that’s it! We have gone all the way from a purely reflection-based approach to solve this problem, to an optimized version that not only ditches reflection entirely, but memory allocations too.</p><h3>Was it worth it?</h3><p>I have prepared a benchmark that compares the 4 different implementation we have discussed. The results are categorized into three scenarios, from “Small” being a simple closure with a couple of captured reference and value types, to “Large” having over a dozen captured fields spread across three different variables copes. Each test case has been run one million times, so the mean execution time you see below is not for a single call to our <strong>GetData</strong> methods. Here are the results:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58e71d39d8e17e4e8b7564e9c71e42e8/href">https://medium.com/media/58e71d39d8e17e4e8b7564e9c71e42e8/href</a></iframe><p>Compared with the baseline being the reflection-based implementation, using dynamic getters is over <strong>1.4x</strong> faster on average, which becomes a whopping <strong>25x</strong> faster with the single getter and the other optimizations! We can see that there is not much difference between the first implementation with dynamic getters and the one with loop unrolling, but doing that intermediate step was still useful to gradually approach the last level of optimization.</p><p>I have setup a full test project that demonstrates all these different techniques and includes the benchmark used to generate the results listed above. You can find it here on GitHub: <a href="https://github.com/Sergio0694/ReflectionToIL"><strong>https://github.com/Sergio0694/ReflectionToIL</strong></a>.</p><p>I hope that no matter your skill level with C# you have enjoyed this post and found it interesting. I definitely had fun working on this project and writings all of this down! I have added links to every single API that I’ve used across all the code snippets, so if you want to get more details on any of them you can just click and read the official MS docs page about it.</p><p>If you spot any mistake in either this post, one of the embedded code snippets or one of the files in the test project, please let me know!</p><h3>Happy coding!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e15cef4b1a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>