<?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 Norm Bryar on Medium]]></title>
        <description><![CDATA[Stories by Norm Bryar on Medium]]></description>
        <link>https://medium.com/@norm.bryar?source=rss-4f1150f0dd91------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QB8o4snAkNSanoxhYT7Vig.jpeg</url>
            <title>Stories by Norm Bryar on Medium</title>
            <link>https://medium.com/@norm.bryar?source=rss-4f1150f0dd91------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 07:06:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@norm.bryar/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[That LeetCode Question’s Value is in the Conversation]]></title>
            <link>https://medium.com/@norm.bryar/that-leetcode-questions-value-is-in-the-conversation-c667cfeb9e69?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/c667cfeb9e69</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Mon, 06 Mar 2023 18:34:29 GMT</pubDate>
            <atom:updated>2023-03-06T18:34:29.539Z</atom:updated>
            <content:encoded><![CDATA[<h4>Good programming interview questions uncover how someone thinks and envisions.</h4><figure><img alt="Have a rich conversation even at the whiteboard" src="https://cdn-images-1.medium.com/max/1024/0*r2GrT-H2v0h-iyS1" /><figcaption>Photo by <a href="https://unsplash.com/@thisisengineering?utm_source=medium&amp;utm_medium=referral">ThisisEngineering RAEng</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A colleague and I were chatting about how to “robustify” an interview question, meaning make stall-resistant, always allowing it to follow the most fruitful path, surfacing demonstrable skills without them being walled-off by a lesser question’s constraints.</p><p>Ideally, an interview question can naturally up- or down-level in detail or principle. Some little tangent-topic sidebar can uncover how broad or deep the waters run. Some little pivot best lets a candidate succeed (perhaps pointing a struggling candidate to a different org role, or perhaps showing you this junior is really a senior).</p><p>To get such insights, you need constant communication. Candidates must explain what they’re thinking as they’re going. Interviewers should ask lots of “why?”, “what factors?”, “where might this go?” (aware of the fine line before randomizing the poor guy/gal).</p><h4>Blooms Taxonomy</h4><p>Mastery, unsurprisingly, is more than reciting facts it’s a spectrum of abilities: applying knowledge to problems, familiar or new; identifying parts that can be extracted or (re-)combined; critiquing and modifying what we do. Benjamin Bloom famously captured this in <a href="https://en.wikipedia.org/wiki/Bloom%27s_taxonomy#Cognitive_domain_(knowledge-based)">Bloom’s Taxonomy</a>.</p><figure><img alt="Bloom’s Taxonomy outlines levels of specificity, complexity, and mastery in learning" src="https://cdn-images-1.medium.com/max/739/0*rkDIOd-TZlvwsEqf.png" /><figcaption>Source <a href="https://en.wikipedia.org/wiki/Bloom%27s_taxonomy#/media/File:BloomsTaxonomy.png">wikipedia</a></figcaption></figure><p>So, … bonus points if the candidate finds an abstraction, solving the question’s use-case as but one application of their general approach. This is partly what we’re trying to sus-out with follow-ups like “What’s the Big-O of this thing?” Though it may inspire other avenues of inquiry.</p><h3>A Leet(-ish) Question</h3><p>The goal of finding a candidate’s Bloom layers hasn’t made me bond too greatly with overly algorithm-centric questions, but in this colleague-chat we discussed a (probably LeetCode?) question:</p><blockquote>Given a large 2D array where each row holds values monotonically increasing, as does each column, find whether a target value exists.</blockquote><pre>...thousands more rows...<br>| 1 | 1 | 1 | 1 |    <br>| 1 | 1 | 2 | 5 |<br>| 3 | 4 | 5 | 5 |<br>| 10| 20| 30| 40|     // target=30 exists twice<br>| 12| 25| 30| 45|<br>| 99| 99| 99| 99|<br>... thousands more rows...</pre><p>Ok, you probably immediately thought <em>BinarySearch</em> could trivially be applied within rows (Knowledge, Comprehension, Application)</p><p>Then likely thought the cagey interviewer wants to see if you’ll suggest pruning the search-space of rows (Comprehension, Application).</p><p>Then you may have felt pruning candidate rows takes two steps: Finding which rows end with values too small to match the target, and which rows start with values too large to match the target (e.g. if target = 30, all rows above 3, 4, 5, 5, and all below 99, 99, 99, 99 needn’t be searched) (Analysis).</p><p>Here’s what I, as an interviewer, would like to hear the candidate ponder. <em>Huh, If only I could BinarySearch on a column instead of a row </em>(Analysis, Synthesis)<em>.</em></p><p>Now we can have a conversation about whether extracting the column into its own array and using Array.BinarySearch as-is would suffice (O(m) space and time copy, defeating the whole purpose of using O(log(m)) binary-search. Comprehension, Analysis)?</p><p>… or better to make some abstraction? Perhaps a new BinarySearch taking 2D arrays with and some column-mode input? Perhaps a pair of classes: an adapter-class surfacing columns as 1D interfaces, and a BinarySearch on that 1D interface. The candidate may jump at one, so I might ask what made this option so attractive. Any others he can think of?</p><p>That conversation is already more interesting (to me) than whether the candidate can recite/re-derive the binary-search algorithm itself.</p><p>That pair-of-classes approach might proceed thusly:</p><pre>public record TwoDArrayColumnSlice&lt;T&gt;(T[,] Source, Index Column) <br>    : IReadOnlyList&lt;T&gt;<br>{<br>    public T this[int index]<br>    {<br>        // Ask pros/cons of explicit index range-check<br>        get =&gt; this.Source[<br>            index,<br>            Column.GetOffset(Source.GetLength(1))];<br>    }<br><br>    public int Count =&gt; this.Source.GetLength(0);<br><br>    //public IEnumerator&lt;T&gt; GetEnumerator() =&gt;<br>    //    throw new NotImplementedException();<br>    <br>    //IEnumerator IEnumerable.GetEnumerator() =&gt;<br>    //    throw new NotImplementedException();<br>}<br>...<br><br>int[,] arr2d = new int[,]<br>    {<br>        { 1, 1, 1, 1, 1 },<br>        { 2, 3, 4, 4, 5 },<br>        { 9, 9, 9, 9, 9 }<br>    };<br>// Get the 1, 5, 9 column<br>var lastColumnSlice = new TwoDArrayColumnSlice&lt;int&gt;( arr2d, ^1 );</pre><p><em>Why </em><a href="https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.ireadonlylist-1?view=net-7.0#properties"><em>IReadOnlyList&lt;T&gt;</em></a><em> ?</em> All we need is the indexer-support and maybe Count. Turns out native C# arrays also implement IReadOnlyList&lt;T&gt; which might be handy, perhaps in a Slice adapter for jagged-arrays like int[][], though an Index arg can be trouble on unequal sized rows. Discuss. (Synthesis, Evaluation)</p><p>The search itself is a tad more involved and, after the tangents so far, the candidate might not have time left to write it given we still haven’t solved the problem posed either. I might first tell them to assume BinarySearch exists, how would they use it? Further discovery desirable abstractions may result.</p><p>A skeletal solution begins to grow.</p><pre>bool found = false;<br>IReadOnlyList&lt;int&gt; col0Slice = new JaggedArrayColumnSlice&lt;int&gt;( sparseArr, 0  );<br>IReadOnlyList&lt;int&gt; colNSlice = new JaggedArrayColumnSlice&lt;int&gt;( sparseArr, ^1 );<br>(found, int rowToEnd)   = col0Slice.BinarySearch( target + 1 );<br>(found, int rowToStart) = colNSlice.BinarySearch( target - 1 );<br><br>// find among the reduced search-space<br>for (int row = rowToStart; row &lt; rowToEnd; ++row )<br>{<br>    // search within row<br>}</pre><p>For instance, finding the rowToStart could be sped-up a bit if we limit candidate rows to [0..rowToEnd], thus suggesting BinarySearch should take optional start and end arguments.</p><p>(Also, one could discuss if the target ± 1 trick should be replaced with a find-first/last-index-of extension, as a search for target itself might otherwise we might find an index it the middle of a range of duplicates. Would such an extension better support floats? Spurring a brief equality-epsilon conversation. Comprehension, Application.)</p><p><em>Why does our new search return a tuple? </em>From early C#,<em> </em><a href="https://learn.microsoft.com/en-us/dotnet/api/system.array.binarysearch?view=net-6.0#system-array-binarysearch-1(-0()-0)">Array.BinarySearch</a> returns the index on match else the ones-complement (~index) of where to insert the target. Kloodgy API design. Discuss. (Evaluation)</p><p>Should time or flow get us here, BinarySearch might look like this:</p><pre>public static class CollectionExtensions<br>{<br>    public static (bool found, int index) BinarySearch&lt;T&gt;(<br>       this IReadOnlyList&lt;T&gt; source,<br>       T   item,<br>       int start = 0,<br>       int end   = -1)<br>    {<br>        end = end &lt; 0<br>            ? source.Count - 1<br>            : end;<br><br>        // This step is avoidable w/ .Net7 numeric types<br>        IComparer&lt;T&gt; comp = Comparer&lt;T&gt;.Default;<br><br>        return BinarySearchInner(<br>            source, comp, item, start, end);<br>    }<br><br>    private static (bool found, int index) BinarySearchInner&lt;T&gt;(<br>        IReadOnlyList&lt;T&gt; source,<br>        IComparer&lt;T&gt;     comparer,<br>        T                item,<br>        int              start,<br>        int              end)<br>    {<br>        int idx = -1;<br>        int cmp = -1;<br>        while (start &lt;= end)<br>        {<br>            idx = (start + end) / 2;<br><br>            cmp = comparer.Compare(source[idx], item);<br>            if (cmp &lt; 0)      start = idx + 1;<br>            else if (cmp &gt; 0) end = idx - 1;<br>            else              return (true, idx);<br>        }<br><br>        // Missing? Return index to insert item at.<br>        return (false, idx + (cmp &lt; 0 ? 1 : 0));<br>    }</pre><p>(See <a href="https://medium.com/@norm.bryar/doubles-or-floats-let-net7-help-ad30a51cbfb5">Doubles or Floats, Let .Net7 Help</a> for limiting generic T to numerics. This story also discusses the floating-point equality problem.)</p><p>Critiquing that algorithm certainly has merit (although BinarySearch actually had quite a <a href="https://en.wikipedia.org/wiki/Binary_search_algorithm#History">history of refinement</a>, so even smart people might not be perfect re-deriving it), but it’s really not that demonstrative of what you want out of your dev day-to-day, is it? The <em>conversation </em>up ’til then was.</p><h3>Conclusion</h3><p>More seasoned developers look for ways to probe multiple levels of mastery in their interview questions. Considering the Bloom Taxonomy might prompt you to think of tangents to bring-up to probe those levels. Even fairly straight-forward algorithm-centric questions can afford such opportunities (though you may find design-centric questions a more natural fit, ideally ones allowing a code-only escape-hatch for devs greener than expected.)</p><p>Thanks for reading. Hope you found the explore fun.</p><p><a href="https://medium.com/@norm.bryar">~Norm Bryar</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c667cfeb9e69" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Truly Leverage C# Structs (Part 2)]]></title>
            <link>https://medium.com/@norm.bryar/truly-leverage-c-structs-part-2-5e808b5be5bd?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e808b5be5bd</guid>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Sun, 29 Jan 2023 18:54:12 GMT</pubDate>
            <atom:updated>2023-01-29T18:54:12.554Z</atom:updated>
            <content:encoded><![CDATA[<h4>Value-type structs in C# deserve time to understand. Here we continue learning to optimize structs, and where the ideas may lead next.</h4><figure><img alt="She knows the value of arrays of structures" src="https://cdn-images-1.medium.com/max/1024/1*t8Xk-6fIQzMOOaj2j46rCg.jpeg" /><figcaption>Photo by Tima Miroshnichenko: <a href="https://www.pexels.com/photo/woman-sitting-near-stacks-of-pink-soda-cases-while-seriously-looking-at-the-camera-8764357/">https://www.pexels.com/photo/woman-sitting-near-stacks-of-pink-soda-cases-while-seriously-looking-at-the-camera-8764357/</a></figcaption></figure><p>In <strong>Part 1</strong>, we examined the pros and cons of struct, had some general advice around size and layout, but only hinted at more advanced concepts, which we’ll dive into here in <strong>Part 2</strong>.</p><p><a href="https://medium.com/@norm.bryar/4a3f707c40ee">Truly Leverage C# Structs (Part 1) | by Norm Bryar | Jan, 2023 | Medium</a></p><h3>Great, structs are smaller. So what?</h3><p>Structs are smaller (indirection memory and object-header gone), and the first insight we want now is that smaller items naturally exploit a key CPU-native performance layer: Caches. Modern CPUs have several caches, some per-core, some per-chip, some glued onto the DDR stick itself. To a modern CPU, every mem I/O is really block-level I/O with neighboring memory-addresses also accessed. If you can arrange your logic so that you’ll next touch memory adjacent to what you just touched, the access will be nearly free! Data strewn about the lawn, though, cause expensive cache-misses.</p><p>Look at this Intel <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/memory-performance-in-a-nutshell.html">Memory Performance in a Nutshell</a> article in the <em>Size, Latency, and Bandwidth</em> section (my summary below, adding a crude asm-ops column).</p><pre>╔═══════════╦══════════╦═══════════════╗<br>║ Mem Type  ║ Clocks*  ║ Asm Analogy** ║<br>╠═══════════╬══════════╬═══════════════╣<br>║ L1 Cache  ║ ~3       ║ fmul (~5)     ║<br>║ L2 Cache  ║ ~12      ║ fsqrt (~27)   ║<br>║ DDR RAM   ║ ~200     ║ fptan (~115)  ║<br>╚═══════════╩══════════╩═══════════════╝<br>* Assuming 1ns * 3B clocks/sec<br>** From Nehalem table of agner.org/optimize/instruction_tables.pdf</pre><p>The implications are that you could have fairly straight-forward logic (multiplies, adds, square-roots) burning 40 clocks, but had you needed to fetch from main-memory (200 clocks to read, 200 more to write the update back out = 400 total) you’d have a 10:1 cache-miss:logic perf overhead.</p><p>The CPU’s pipeline can’t execute that far ahead (e.g. ~100μ-ops) while waiting, so really all other instructions are stalled waiting on RAM, even ones that could have executed without I/O (and with multiple ALUs, FPUs, etc. per CPU, i.e. multiple instructions per clock-tick, that’s painful).</p><p>We devs are trained to focus on <em>logic</em> (and so does the compiler / JIT’r / optimizer). Devs are less often looking at <em>mem-access</em> (and the JIT’r not at all). Moreover, some profilers don’t distinguish fetch vs. execute; our mem-dominated 10:1 above might misleadingly show as “100% CPU”. So this table might have come as a surprise.</p><h4>Packing-Advice Continued</h4><p>Improving so called “temporal-locality” (things used near each other time are stored near each other in space) takes engineering-effort, deliberate investigation into which use-cases need which subsets of fields. It’s a cage-match, the dev matching wits against the use-case. Here’s some more general advice.</p><ul><li><strong>Array-of-Structs Rules the Roost</strong> <br>Continuing <strong>Part1</strong>’s advice, we’d surmise an array of <em>objects</em> only has the next object <em>reference-address</em> in cache, but that object itself is God knows where, still un-cached. An <strong>array of structs</strong>, however, makes those elements contiguous, so a[i+1] is right there ready same as a[i]. Hopefully.</li><li><strong>Avoid Balls of Mud</strong><br>Your struct might still be too fat to fit 2+ (or even 1!) per cache-line. <br>A good general-purpose size is ≤ 64 bytes, or integer divisors thereof. Fields beyond 64B might need another main-memory fetch — not the end of the world, certainly Unity’s DOTs types tend heavier, but I’d advise hot fields go first in the struct, colder ones at the tail.</li><li><strong>Ditch Some Fields, Cache Others </strong><br>OOP classes sometimes have a problem that, in adding methods to data, we find we need more data for the methods: To the banana, we have to add the gorilla for sake of the hold() method. If the data have different interpretations, it may be best to cut along those lines to optimize structs for them. (Now new data-transform overhead? Benchmark.) <br>OOP classes may call helper classes that re-execute lookups, etc., that ultimately are loop-invariant. Break that encapsulation and move the lookup outside the loop for perf.</li><li><strong>Arrange for Temporal Locality</strong> <br>By now you’ve guessed: if N fields are used together by the same routine (in particular, a hot one), place them near each other, ideally fitting on the same cache-line (64B partition) together. <br>A good mindset: don’t focus on the M operations you may want on any one element, focus on the 1–2 key operations you need to do and on P elements at a time.<br>(One tenant in a broader <em>Data-Oriented Design</em> approach, see <em>References</em>)</li><li><strong>Prefer Sequential Access … </strong><br>When you access memory predictably (always same direction, whichever way that is), the CPU may pull-in the next cache-line in advance. For one-pass operations (max(), avg(), …) that’s great.<br>(And we remember C# is <a href="https://en.wikipedia.org/wiki/Row-_and_column-major_order">row-major</a>, of course ;- )</li><li><strong>…Except if Revisiting Elements</strong><br>For n-pass algorithms, repeated sequential access of large data risks expensive amnesia: cache-line arr[j..(j+k)] has evicted arr[0..k]. <br><a href="https://www.intel.com/content/www/us/en/developer/articles/technical/how-to-use-loop-blocking-to-optimize-memory-use-on-32-bit-intel-architecture.html">Loop-blocking</a> on matrix-multiplication is the poster-child example of not moving on while there’s still riches at your feet. <br>This notion’s taken further with Cache-Oblivious algorithms below.</li><li><strong>Pick Smaller Field-Types!</strong> <br>Your use-case might not need the full range or precision of those orthodox, reflex-chosen datatypes we default to for fields. Pick fields half the size, you get twice as many struct elements on the cache-line (potentially more if struct-of-structs can now remove padding, etc.)</li></ul><h4>About Smaller Data-Types</h4><p>You might want to review some of the range/precision tradeoffs here.</p><p><a href="https://medium.com/@norm.bryar/doubles-or-floats-let-net7-help-ad30a51cbfb5">Doubles or Floats, Let .Net 7 Help</a></p><p><strong>Bit-masking/data-folding</strong> (perhaps via [Flags] enum MyFlags : ushort) or BitVector32) could shrink, say, 12 bools (12B optimally packed) into a 2- or 4-byte field. Bit-masking/shifting may or may not be problematic, so benchmark of course.</p><p>Too many bools can also be a smell, and an opportunity to further specialize structs. Consider, too, that an isDirty bool meant to avoid some cheap-to-compute-and-data-already-on-hand transform might incur a branch-prediction-miss costing more than the transform (but nowhere near as costly as an L3 miss, so don’t forget the <em>data-on-hand </em>thing above). Pre-partitioning the data then applying relevant Func&lt;&gt; to each group might out-do branching or virtual methods.</p><p><strong>‘Object’-Graphs of Structs : </strong>Imagine we create a giant collection of structs, persisted <em>en toto</em>. We can then load this blob at startup and create Memory&lt;T&gt; atop it, with all the physical relationships between entities preserved intact, regardless of the real physical memory address now. We’ve turned all 64-bit references into 32b (or 16b or …) offsets, further trimming overall mem!</p><h4>The False-Sharing Trap</h4><p>If you parallelize your walk through the data, be sure to band the data in large enough blocks that they’re not modifying the same cache-line. Worse, don’t do things like have all P threads write to the same aggregation-output object or collection. This would cause what’s called <a href="https://iditect.com/blog/false-sharing-and-cache-lines.html">false-sharing</a>: CPU3 has touched a record on a cache-line that CPU0, 1, and 2 are also using, so we have to pay the cost of flushing the write, then re-loading those 3 other cache-lines.</p><p>Set intermediate results to (stack-based) local variables then do some post-loop, final-phase harvest.</p><h4>Cache-Oblivious Programming</h4><p>Mindfulness of cache-to-RAM (or more southward still) latency-differences has given birth to a branch of algorithm research: Cache-Aware and Cache-Oblivious programs. (“Oblivious” is a misnomer; here meaning not tuned to a specific CPU’s <em>values </em>for cache-line-size, line associativity degree, hierarchy-levels, write-thru/write-back choice, etc., yet aware of exploiting their <em>existence</em> in the abstract.) Check the <strong>Demaine</strong> link in the References.</p><h3>Then There’s Struct-of-Arrays</h3><p>We’ve been assuming an enity-centric model, Array-of-Structs, in this article. Taking cache-line concerns even further, one could “swizzle” the data-model into a <strong>Struct-of-Arrays</strong>.</p><pre>// AoS view<br>public struct Thingie<br>{<br>    public int X;<br>    public int Y;<br>    public int Z;<br>}<br><br>// SoA view<br>public class ThingieComponents<br>{<br>    public int[] Xs;<br>    public int[] Ys;<br>    public int[] Zs;<br>}</pre><p>Its advantages: a) it gives essentially column-major behavior, which several use-cases prefer anyway; b) this may better fit vectorized single-instruction, multiple-data (<strong>SIMD</strong>) processing as Intel describes <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/how-to-manipulate-data-structure-to-optimize-memory-use-on-32-bit-intel-architecture.html">here</a> and <a href="https://www.intel.com/content/www/us/en/developer/videos/part-6-strip-mining-for-vectorization.html?wapkw=strip-mining">here</a>, or perhaps to GPUs; and c) you now have options to lazy-load or early-flush ‘columns’ as depending on needs at hand. Typically you’ve a struct that holds context common to all data-arrays, which typically are all the same element-count so the ordinal-index into each could give the complete picture of an un-swizzled entity.</p><p>As with all projections (the 1:K class:struct ones for K hot-cases or AoS:SoA swizzles), you should account for the transforms use of CPU and mem, caching or otherwise amortizing the cost of projection, if you have to mix your formats. But SoA is a major technique in your tool-chest.</p><p><strong>Object-Graph via SoA</strong>: You can ditch back-pointers from child Node to parent via expressing a hierarchy of depth N via N distinct Node[] arrays. Level[2][*] holding the parents of those nodes in Level[3][*], say. The current sum of Level[2][0..k].ChildCount tells you where the k-th parent’s children start in Level[3][*].</p><h3>Tools</h3><p>Cache-misses are captured in CPU-counters (see <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/performance-counter-monitor.html">Intel PCM</a>) and several tools support reading these. To see if you might have a problem on a given snippet, it might suffice to use <a href="https://adamsitnik.com/Hardware-Counters-Diagnoser/">BenchmarkDotNet</a></p><pre>[MemoryDiagnoser]<br>[HardwareCountersAttribute(<br>    HardwareCounter.LlcMisses,   // last-level-cache (e.g. L3) <br>    HardwareCounter.CacheMisses  // ???<br>  )]<br>public class MyBenchmarkSuite<br>{<br>    [Benchmark] public int CurrentImpl() { ... }</pre><p>For more granularity, some profilers such as Intel’s VTune allow an every <a href="https://www.intel.com/content/www/us/en/developer/articles/technical/understanding-how-general-exploration-works-in-intel-vtune-amplifier-xe.html">Nth counter-tick interrupt</a> to capture IP-address, giving (rough) instruction-level attribution.</p><p>At this level, I don’t think many static code-analysis packages exist to help you, so bringing runtime tools to bear seems your best choice.</p><h3>Conclusion</h3><p>Re-visiting the data-model for hot-path concerns may have you reaching for structs, which should also make you ask about cache. The ideal composition of such a struct tailored for cache will typically aim to serve fewer use-cases, a hot subset of those a class might serve. As is often true, generality and efficiency tend to be at odds. Don’t always fall into the rut of designing structs the same way you’d have done classes.</p><p>One can successfully use structs (as <strong>Part 1</strong> concluded) without the deeper insight of cache memory-hierarchies, but that extra knowledge is part of “craft”, evergreen and transferrable. It can help you on server-side code, in GPUs, or on mobile devices (wasting CPU dragging sparse cache-lines about is wasting battery, etc.). It can help across domains — gaming, simulation, or even machine-learning.</p><p>A more functional-programming-ish/set-theoretic styled, data-before-code approach, called by some <em>Data-Oriented Design, </em>may guide your perf journey (if not overall product simplicity and agility, per its adherents).</p><p>Hopefully you’ve found the explore interesting.</p><p><a href="https://medium.com/@norm.bryar">~Norm Bryar</a></p><h3>Resource Links for the Deeply Curious</h3><ul><li>Scott Meyers’ <a href="https://www.youtube.com/watch?v=WDIkqP4JbkE&amp;list=PL7Dba4GxNAusFucZ6k5fQusT1UEygy2zs&amp;index=11">Cpu Caches and Why You Care</a> video</li><li>Mike Acton’s <a href="https://www.youtube.com/watch?v=rX0ItVEVjHc&amp;list=PL7Dba4GxNAusFucZ6k5fQusT1UEygy2zs">Data-Oriented Design and C++</a> video<br>DoD puts a name to a set of practices that have stood the test of time.</li><li>Aras Pranckevičius <a href="https://aras-p.info/texts/files/2018Academy%20-%20ECS-DoD.pdf">Entity Component Systems &amp; Data Oriented Design</a></li><li>Richard Fabian’s <a href="https://www.dataorienteddesign.com/dodbook/">Data-Oriented Design</a> book excerpts</li><li>Erik Demaine’s <a href="http://erikdemaine.org/papers/BRICS2002/paper.pdf">Cache Oblivious Algorithms and Data-Structures</a></li><li>Sergiy Migdalskiy <a href="https://www.youtube.com/watch?v=Nsf2_Au6KxU">Performance Optimization, SIMD and Cache</a> video.</li><li><a href="https://medium.com/@norm.bryar/4a3f707c40ee">Truly Leverage C# Structs (Part 1) | by Norm Bryar | Jan, 2023 | Medium</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e808b5be5bd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Truly Leverage C# Structs (Part 1)]]></title>
            <link>https://medium.com/@norm.bryar/truly-leverage-c-structs-part-1-4a3f707c40ee?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3f707c40ee</guid>
            <category><![CDATA[better-programming]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 03:03:46 GMT</pubDate>
            <atom:updated>2023-01-29T18:55:48.551Z</atom:updated>
            <content:encoded><![CDATA[<h4>A lot has been said about value-type structs in C#, because a lot <em>should</em> be said about them. Here’s the scoop on choosing, and best using, structs.</h4><figure><img alt="The beauty of arrays of well-packed structures" src="https://cdn-images-1.medium.com/max/1024/1*JbJtrPXpwrvdgRY7LGw7YA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@sumitmangela?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Sumit Mangela</a> on <a href="https://unsplash.com/photos/ASM0H3ul2yo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>You’ve no doubt seen the struct keyword, used in much that same context as the class keyword. You likely also know that the tuple-syntax, e.g. public (int Code, string Msg) DoStuff();, lowers to ValueTuple&lt;int, string&gt; which is a struct. These are pass-by-value types, basically stored in-line within their enclosing scope. Bear with me as I give a quick overview why struct gives devs an approach-avoidance conflict.</p><h3>Structs: The Good, Bad, and Ugly</h3><h4>Pros</h4><ul><li>Removes indirection.<br>A collection of reference-<em>objects </em>(i.e. class instances) always requires traversing an address to get to the instance’s fields: 1 hop into the collection, 1 more hop into the element. And if a class’ field is also a class, a third hop to get to those elements. <br>But <em>structs </em>inline all this, eliminating extra hops.</li><li>More compact.<br>Objects have <a href="https://devblogs.microsoft.com/premier-developer/managed-object-internals-part-1-layout/">object-header or virtual method-table overhead</a> in their representation. On x64, 16 bytes of every object serve overhead. In collections of non-polymorphic class-objects, and if per-object locks aren’t used, the overhead is waste for you. <br>Structs eliminate this overhead.</li><li>More cache-line friendly.<br>No indirection means array elements sit contiguous in memory. No object-overhead makes that memory compact. Structs thus lend themselves well to the memory speed-ups in-built into the CPU.</li><li>Lessens garbage-collection overhead. <br>With objects, even a local variable is created on the heap then must be garbage-collected. Struct local variables are created on the stack. Struct fields are inlined in the enclosing entity (even if it is an object on the heap, thus not separately tracked by GC).<br><a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/stackalloc">Stackalloc</a> and <a href="https://adamsitnik.com/Span/">Span&lt;T&gt;</a> of structs mean containing arrays aren’t GC’d either.</li><li>Help avoid mutation.<br>Object references can allow callees to (unexpectedly) make mutating changes, a source of bugs. Structs use copy-by-val, or thein param, to keep the original pristine.</li></ul><h4>Cons</h4><ul><li>Less forgiving.<br>Nuances here mean innocent mistakes can torpedo your gains.<br>* <a href="https://thedotnetguide.com/csharp-boxing-and-unboxing/">Boxing</a> / unboxing brings the heap back into the picture, and forces copying the struct’s data-fields at each such heap/stack transition.<br>* Defensive copies arise when the compiler doesn’t know a struct-method doesn’t mutate state. <br>* Evolution, either in adding fields or use in a new context, can re-expose you to said torpedoes.</li><li>Costly default comparison.<br>* Forgetting to override Equals and GetHashCode, may saddle you with very slow reflection.<br>* A struct’s default GetHashCode, in particular, is criminally negligent!</li><li>[StructLayout(<a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.layoutkind?view=net-7.0#fields">LayoutKind</a>)] Effects.<br>* Aggressive packing, e.g. Pack=1, could split reads across non-native-type-size boundaries, e.g. to read an un-aligned long (8-bytes) would require 2 reads, first (_,_,_,_,_,_,X,X) then (X,X,X,X,X,X,_,_), shifting each, and a bit-OR op to re-assemble. All waste. <br>* Naïve field-ordering, e.g. a bool then a double, could add 7 bytes of padding after the bool to keep the larger double native-size-aligned (true even if you didn’t do naughty things with Pack=).</li><li>Structs lack inheritance<br>Polymorphism of different ‘base’ elements breaks array packing.</li><li>Misc other dev-unfamiliar idioms.<br>* Few folks have extensive experience with keywords ref, ref return, in, and readonly applied to structs, increasing the chance for bugs. <br>* Ref/in/out params are banned from async-methods due to scope-lifetime concerns. Your struct work may collide with async work. <br>* Generic constraints (Foo&lt;T&gt; where T:struct or where T:class) and nullable-reference syntax (DoStuff( T? blah){…}) don’t always easily mix. The compiler won’t use generic-constraint declarations to aid overload resolution. Your devs may have to learn tricks like <a href="https://medium.com/@norm.bryar/embrace-the-nullable-reference-95759737cdda">nullability-attributes</a>, e.g. Go([MaybeNull] T arg) to now accommodate structs.<br>* And don’t get me started about <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct">ref struct</a>.</li></ul><h3>General Advice</h3><p>So, how do you avoid the cons?</p><h4>Avoiding Boxing</h4><p>The ref keyword is a major way to avoid boxing, but it only works when the lifetime scope plainly keeps the memory-location live to allow a reference to it (if the stack has unwound, the memory might be gone or re-purposed). Of course, avoid declaring methods that take only an object parameter, which will surely box structs. I know this is at odds for a popular extension technique, Dictionary&lt;string, object&gt;</p><p>A common case is your struct implements some interface(s). Beware just calling library methods with that interface as a param will force the struct to be boxed. Hopefully, you’re the author of the (extension-)methods and can make a generic, struct-centric overload:</p><pre>public void AvoidsBoxing&lt;T&gt;( T valStruct )<br>    where T : IInterface  // compiler knows Method() will exist...<br>{<br>    valStruct.Method(…);  // ...still a callvirt, but non-boxed<br>}<br><br>// struct is boxed to get an IInterface reference, <br>// then has to do a v-table lookup to get to Method().<br>public void OopseBoxing( IInterface boxedStruct ) =&gt;<br>    boxedStruct.Method(…);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*_vLKMLRoa84eYYV_IXyz5A.png" /><figcaption>LINQPad MSIL showing box op (at IL_0017)</figcaption></figure><p>For a surprising example of boxing impact, look at Matt Warren’s <a href="https://mattwarren.org/2016/02/17/adventures-in-benchmarking-memory-allocations/">Adventures in Benchmarking</a> blog under the <em>Dictionary vs IDictionary </em>section.</p><h4>Avoiding (Defensive) Copy Expense</h4><p>The old advice that a struct should be small (~16bytes) is a tad onerous; when you can just use ref or in to avoid copy-constructing all those fields. As mentioned above, however, the compiler has to be certain the struct’s lifetime safely allows this.</p><p>Sadly, ref strips any immutability guarantee you might have wanted. This is where the the in keyword comes in, acting kind’a like const Foo&amp; in C++. With in, the compiler keeps the original pristine, … but it does so by inserting defensive-copy ops on any method (and remember, a property-getter is just a method) unless adorned with readonly. No kidding, the compiler’s stupid this way, even things short enough to inline and clearly are immutable need the readonly keyword.</p><p>One can mark the whole struct readonly (and consider a record-style <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-10.0/record-structs#allow-with-expression-on-structs">with-expression</a> to support to copy-on-write, but note it does a full-copy before the with { … } inits). But readonly <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/struct#readonly-instance-members">methods</a> such as <a href="https://docs.microsoft.com/en-us/dotnet/csharp/write-safe-efficient-code#declare-readonly-members-for-mutable-structs">property-getters</a> can be more surgical. Warn your team, lest someone forget their new method needs this keyword.</p><p>I wish the story with Analyzer support were better to warn you if a defensive-copy occurs. The <a href="https://www.nuget.org/packages/ErrorProne.NET.Structs/">ErrorProne.Net.Structs</a> analyzer would have been my first choice but as of this writing (Jan. 2023, VS 17.4.0), it fails builds with AD0001 “…InvalidCast…” errors. On earlier VS, there were also some false-positives, e.g. on ReadOnlySpan&lt;T&gt; where defensive copy size is actually negligible. You might want to ‘fork’ the logic into your team’s analyzer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*BU9w7AXGKtRuw7ASXUXBIQ.png" /><figcaption>LINQPad showing defensive copy</figcaption></figure><h4>Avoiding Default Equality Woes</h4><p>I’m tempted to just always hand-code an IEquatable implementation.</p><p>You MUST beware struct&#39;s default GetHashCode has unforgivable behavior. It <strong>only looks at the <em>first</em> field in the struct! </strong>Seriously. If that first field holds low-cardiality, poorly discriminative values (.State=”California”), then your O(1) Dictionary&lt;,&gt; becomes an O(1_000_000) list. Maybe you’re not using this struct as a key in HashSet/Dictionary, but will the next dev try to?</p><p>Though adding a maintenance burden, Equals might be good to hand-implement. I’m not sure how often <a href="https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/records#characteristics-of-records">record struct</a> might emit an Equals with a fast memcmp of blittable fields (nor if ValueTuple ever does so), but I think its typical choice of EqualityComparer&lt;T&gt;Default.Equals() is slower than I’d have done by hand (esp. given dev knowledge on ordering compares by cardinality / early-out likelihood). Oh, and mark them readonly, just in case.</p><h4>Struct Layout Hazards</h4><p>Perhaps for the advanced, … but who doesn’t want to be more advanced?</p><p>For class-object types, the compiler defaults to LayoutKind.Auto, re-organizing the fields you’ve declared in size-descending order (sub-sorted by your declared ordering). This keeps every field safely aligned on a multiple of its own length, avoiding split-reads.</p><pre>[StructLayout( LayoutKind.Auto )]<br>internal record struct SomeAuto( byte B, long L, int I, long Z, long G );</pre><p>Using the <a href="https://github.com/SergeyTeplyakov/ObjectLayoutInspector">Object Layout Inspector</a> (<a href="https://www.nuget.org/packages/ObjectLayoutInspector/">NuGet</a>), we see Auto save us.</p><pre>Type layout for &#39;SomeAuto&#39;<br>Size: 32 bytes. Paddings: 3 bytes (%9 of empty space)<br>|===========================================|<br>|   0-7: Int64 &lt;L&gt;k__BackingField (8 bytes) |   👈 new order L, Z, G, I, B <br>|-------------------------------------------|<br>|  8-15: Int64 &lt;Z&gt;k__BackingField (8 bytes) |<br>|-------------------------------------------|<br>| 16-23: Int64 &lt;G&gt;k__BackingField (8 bytes) |<br>|-------------------------------------------|<br>| 24-27: Int32 &lt;I&gt;k__BackingField (4 bytes) |<br>|-------------------------------------------|<br>|    28: Byte &lt;B&gt;k__BackingField (1 byte)   |<br>|-------------------------------------------|<br>| 29-31: padding (3 bytes)                  |<br>|===========================================|</pre><p>But a struct may or may not be automatically re-arranged. By default, according to docs, structs that don’t hold any reference-types within them use LayoutKind.Sequential . Thus what order you told it to use, no matter your level of sobriety or sophistication, incurs whatever extra padding is needed to keep fields at their native-size alignment.</p><pre>internal record struct NaiveStruct(byte B, int I, byte B2, ushort S );</pre><pre>Type layout for &#39;NaiveStruct&#39;<br>Size: 12 bytes. Paddings: 4 bytes (%33 of empty space)   👈 OUCH!<br>|============================================|<br>|     0: Byte &lt;B&gt;k__BackingField (1 byte)    |<br>|--------------------------------------------|<br>|   1-3: padding (3 bytes)                   |<br>|--------------------------------------------|<br>|   4-7: Int32 &lt;I&gt;k__BackingField (4 bytes)  |<br>|--------------------------------------------|<br>|     8: Byte &lt;B2&gt;k__BackingField (1 byte)   |<br>|--------------------------------------------|<br>|     9: padding (1 byte)                    |<br>|--------------------------------------------|<br>| 10-11: UInt16 &lt;S&gt;k__BackingField (2 bytes) |<br>|============================================|<br><br>LayoutKind.Auto would be 8 bytes, 0% empty-space!</pre><p>Personally, I suspect it’s a good practice to always include the [StructLayout(LayoutKind.Xxx)] attribute on structs to announce your intent and prompt your code-reviewers to look-out for bad padding (which you’ll help them to recognize by adding some of my <em>Resource Links</em> below to your team wiki, yeah?).</p><p>Omit setting the Pack field unless you’re having to do cross-platform interop (which might be best on a dedicated DTO type, not the runtime struct you’re hoping to optimize perf with).</p><p>A weird behavior I observe when using <a href="https://www.nuget.org/packages/ObjectLayoutInspector/0.1.4">ObjectLayoutInspector</a> is that if the struct holds any reference-type fields (e.g. a string or an array), any explicit LayoutKind you applied is <em>silently</em> overridden to beAuto. I’ve yet to see this described in any of the official docs. As to why, perhaps Microsoft feels interop/binary-persistence might be out-of-the-picture once managed-memory references enter the scene, so … Analyzer rule sorely needed here!</p><h4>Do the Pros Outweigh the Cons?</h4><p>Ok, so you’ve seen some traps and the mindfulness needed to avoid them. Possibly this explains why you’re not seeing structs everywhere. But is that warranted?</p><p>Many successful apps can live and grow blissfully free of structs. But some domains <em>need </em>to consider more bare-metal behaviors and constraints, even if just for perf-critical hot-paths. Clever use of structs may save the day.</p><p>If you’re going the struct route, I think you’d want to also consider related changes to really leverage these finicky, princess-and-the-pea data-types, tricks that may help tip the pros/cons scale decisively. Such tricks will appear in the Part 2 article to follow. Teaser: cache-lines make a cameo.</p><h3>Esoterica with Layout</h3><p>We’ll close with a few simple, but less advertised struct tricks.</p><h4>Union Fields</h4><p>Sometimes it have both component- and composite-fields in a union-struct, e.g. have an int consilidate R, G, B byte color channels.</p><pre>[StructLayout(LayoutKind.Explicit)]<br>public struct RGBA<br>{<br>    [FieldOffset(0)] public byte Blue;<br>    [FieldOffset(1)] public byte Green;<br>    [FieldOffset(2)] public byte Red;<br>    [FieldOffset(3)] public byte Alpha;<br>    [FieldOffset(0)] public uint Quad;  // DWORD of Red, Green, Blue, Alpha<br><br>    public RGBA( uint q )<br>    {<br>        this.Quad = q;<br>        // Unsafe.SkipInit( out this.Red ); // optionally list comp fields <br>        Unsafe.SkipInit( out this.Green );<br>        Unsafe.SkipInit( out this.Blue );<br>        Unsafe.SkipInit( out this.Alpha );<br>    }<br><br>    public RGBA( byte r, byte g, byte b, byte a = (byte) 0xFF )<br>    {<br>        this.Red   = r;<br>        this.Green = g;<br>        this.Blue  = b;<br>        this.Alpha = a;<br>        Unsafe.SkipInit( out this.Quad );<br>    }</pre><p>One could union fields of other numeric type, e.g. [Flags] enum Fruit : byte { Apple=1, Banana=2, Date=4, Kiwi=8 }. The point is the Equals and GHC(), persistence, etc. could operate on just the uint Quad.</p><h4>Ref Variables and Collections</h4><p>Familiarize yourself with the ref keyword for parameters, locals, and even returns (of ref or array params). This allows you to point at (and mutate) a struct without the cost of copy-construction. For arrays, this is straight-forward.</p><p>For Dictionary collections, look at <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.collectionsmarshal?view=net-7.0#methods">CollectionsMarshal</a> utility methods (and perhaps the <a href="https://medium.com/@norm.bryar/dictionaries-and-spans-7b72433da75d">Dictionaries and Spans</a> article ;- )</p><h4>Inline Arrays</h4><p>In ‘safe’ code, an array (even of primitive-elements) would be a reference. However, by enabling ‘unsafe’ code you should be able to inline a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code#fixed-size-buffers">fixed-size buffer</a> primitive array, e.g. public fixed byte sha1Hash[20];</p><pre>[StructLayout( LayoutKind.Sequential )]<br>internal unsafe struct InlineArr<br>{<br>    public fixed byte sha1Hash[20];<br>    public ushort major;<br>    public ushort minor;<br>    public ushort rev;<br>}<br>...<br>TypeLayout.PrintLayout&lt;InlineArr&gt;();</pre><p>yields</p><pre>Type layout for &#39;InlineArr&#39;<br>Size: 26 bytes. Paddings: 0 bytes (%0 of empty space)<br>|=====================================================|<br>|  0-19: &lt;sha1Hash&gt;e__FixedBuffer sha1Hash (20 bytes) |<br>| |========================================|          |<br>| |     0: Byte FixedElementField (1 byte) |          |<br>| |----------------------------------------|          |<br>| |  1-19: padding (19 bytes)              |          |<br>| |========================================|          |<br>|-----------------------------------------------------|<br>| 20-21: UInt16 major (2 bytes)                       |<br>|-----------------------------------------------------|<br>| 22-23: UInt16 minor (2 bytes)                       |<br>|-----------------------------------------------------|<br>| 24-25: UInt16 rev (2 bytes)                         |<br>|=====================================================|</pre><p>This might dovetail with, say, C#11’s utf-8 string-literals, etc. But should one add fixed-array fields to their struct? You can weigh its effect on CPU cache-line population after reading the Part 2 article to come.</p><h3>Conclusion</h3><p>I <em>told </em>you C# structs was a big and nuanced topic, didn’t I?</p><p>You can pretty quickly change a class to a (record-)struct and benchmark if you get a perf or mem win. But, as nearly always the case, the more you know, the better (and less risky) it gets. Try to pick better data-types, intelligently inline hot data and split into a reference object cold data, and be mindful of access-patterns to truly leverage what that foray into structs has started for you.</p><p>These concepts are evergreen and portable. Insights gained here will serve you your whole career long, so I highly advise taking a tour through the links below.</p><p>We continue our journey in <strong>Part 2</strong>.</p><p><a href="https://medium.com/@norm.bryar/truly-leverage-c-structs-part-2-5e808b5be5bd">Truly Leverage C# Structs (Part 2) | by Norm Bryar | Jan, 2023 | Medium</a></p><p><a href="https://medium.com/@norm.bryar">~Norm Bryar</a></p><h3>Resource Links for the Deeply Curious</h3><ul><li><a href="https://docs.microsoft.com/en-us/dotnet/csharp/write-safe-efficient-code">Write safe, efficient code</a></li><li><a href="https://www.jacksondunstan.com/articles/3860">How to Write Faster Code Than 90% of Programmers</a></li><li><a href="https://adamsitnik.com/Value-Types-vs-Reference-Types/">Adam Sitnik’s ValueTypes vs RefernceTypes</a></li><li>Sergey Tepliakov’s <a href="https://devblogs.microsoft.com/premier-developer/performance-traps-of-ref-locals-and-ref-returns-in-c/">Performance traps of ref-locals</a></li><li>Sergey Tepliakov’s <a href="https://devblogs.microsoft.com/premier-developer/managed-object-internals-part-4-fields-layout/">Object Internals Part 4: Fields Layout</a></li><li><a href="http://www.catb.org/esr/structure-packing/">The Lost Art of Structure Packing</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3f707c40ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faster use of bool?]]></title>
            <link>https://medium.com/@norm.bryar/faster-use-of-bool-f541d349fce4?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/f541d349fce4</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Sun, 25 Dec 2022 00:35:47 GMT</pubDate>
            <atom:updated>2022-12-25T19:43:43.197Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*JnKYNgSqQIb2on-uoMS4tA.jpeg" /><figcaption><a href="https://allthetropes.org/wiki/A_Wolf_in_Sheep&#39;s_Clothing">A Wolf in Sheep’s Clothing — All The Tropes</a></figcaption></figure><p>Sometimes, you’d like to avoid branching, and would rather just be able to treat a bool as a 1 or a 0. Sadly, C# doesn’t have a performant, native way to do that conversion. But, with caveats, you might be able to add one.</p><h3>Branchless Programming</h3><p><em>Why care?</em> As great as modern CPU branch-prediction is, sometimes you have quite random test-conditions which would cause the CPU to hit <strong>branch-mispredict stalls</strong>, where speculative-execution work pipelined ahead of the arrival of the test-condition has to be thrown-out, causing delay as the alternate path instead runs. Moreover, the branch-prediction buffer is finite size, so potentially the CPU’s evicted history of another hot branch in effort to cache this unpredictable one. Avoiding such stalls motivates the set of techniques known as <em>Branchless Programming</em>.</p><p>For complex Boolean expressions, there could be many intermediate bool terms. <em>Short-circuit evaluation</em> is performed in an attempt to eliminate costly expressions once their evaluation can’t countermand the result so far, e.g. inf() || g(), a true f() allows us to skip the expensive g() call. Each || or &amp;&amp; incurs the risk of a stall, a cost absolutely worth paying if g() hits a database or something. But if f() and g() are trivial to compute, might be faster to just run ’em both and bit-wise combine results.</p><pre>// Materialize lookup values as data<br>private static readonly string[] Answers = new[] { &quot;Boo&quot;, &quot;Yay&quot; };<br><br>int bool1AsInt = boolAsInt( a &gt; 50 );  // 👈 TBD some magic converter<br>int bool2AsInt = boolAsInt( a != b );<br>int bool3AsInt = ...;<br><br>// Don&#39;t incur short-circuit/early-out cost if bool terms are trivial<br>int testCond   = ((bool1AsInt &amp; bool2AsInt) | bool3AsInt);<br><br>// Don&#39;t incur if-else or ternary-op cost; array-indexing is faster<br>string result = Answers[ testCond ]; </pre><p>(Answers[] encoding logic as data is a lost-art technique devs should arguably choose more often when data’s expressible as small arrays.)</p><p>In C#, the obvious choices for converting bool to int are a ternary-operator tAsInt = t ? 1 : 0 or Convert.ToInt32(t). The option we’ll discuss here, though, is pointer-casting.</p><pre>public static class BoolExtensions<br>{<br>    [MethodImpl(MethodImplOptions.AggressiveInlining)]<br>    public unsafe static int AsInt(this bool b)  // 👈 compile to allow unsafe blocks<br>        =&gt; (int)(*(byte*)(&amp;b));    // Dodgy.  See below.<br>}</pre><p>Here we’re re-interpreting the memory-location of a bool to be a byte, dereferencing it as such, then promoting byte to int. The cast ought to be safe as sizeof(bool) == sizeof(byte) and <a href="https://en.wikipedia.org/wiki/Endianness">endian</a>-invariant. Size being important just in case it’s used in a tightly-packed context (or maybe with <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.skiplocalsinitattribute?view=net-7.0">[SkipLocalsInit]</a> where padding isn’t safely zero’d) to avoid contamination by neighboring bytes.</p><p>Parameter b is stack-resident so we can take its address without having to worry about fixed(…) GC-pinning any heap-memory.</p><p>Our big worry is can we assume bools only hold {0, 1}¹. Well, mostly yes (I’ve never seen it outside this range, except when we almost begged for type abuse, … but 1st caveat). Turns out, if bool f() somehow returned, say, 0xAA as its bool while g() returned true, the compare if (f() == g()) would be true! When bool types are compared, their <em>non-zero-ness</em> gets compared, not their values, likely a concession Microsoft made to better support interop. But 0xAA would wreak havoc on our Answers[] above. One could do a safer convert like so²:</p><pre>public static class BoolExtensions<br>{<br>    // This version should be much more interop-safe!<br>    [MethodImpl(MethodImplOptions.AggressiveInlining)]<br>    public unsafe static int AsInt(this bool b) =&gt;<br>        NonNormalizedAsInt( (*(byte*)&amp;b) != 0 );<br>    <br>    [MethodImpl(MethodImplOptions.AggressiveInlining)]<br>    private unsafe static int NonNormalizedAsInt(bool b) =&gt;<br>        (int)(*(byte*)(&amp;b));<br>}</pre><h4>How do the alternatives stack up?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*y9e2p4JdQjKmp5Ql1br_EQ.png" /></figure><pre>[InProcess, GcServer, MemoryDiagnoser,<br> ReturnValueValidator, <br> Orderer(SummaryOrderPolicy.FastestToSlowest)]<br>public class BenchmarkTests<br>{<br>    private bool[] data;<br><br>    [GlobalSetup]<br>    public void Setup()<br>    {<br>        Random rnd = new(123);<br>        data = Enumerable.Range(0, 1_000)<br>                         .Select(_ =&gt; rnd.NextDouble() &lt; 0.5)<br>                         .ToArray();<br>    }<br>    <br>    [Benchmark(Baseline = true)]<br>    public int Ternary()<br>    {<br>        int sum = 0;<br>        for (int i = 0; i &lt; data.Length; ++i)<br>        {<br>            sum += data[ i ] ? 1 : 0;<br>        }<br>        return sum;<br>    }<br>    <br>    [Benchmark]<br>    public int ConvertToInt()<br>    {<br>        int sum = 0;<br>        for (int i = 0; i &lt; data.Length; ++i)<br>        {<br>            sum += Convert.ToInt32( data[ i ] );<br>        }<br>        return sum;<br>    }<br><br>    [Benchmark]<br>    public int UnsafeCast()<br>    {<br>        int sum = 0;<br>        for (int i = 0; i &lt; data.Length; ++i)<br>        {<br>          sum += data[ i ].AsInt();<br>        }<br>        return sum;<br>    }<br>}</pre><p>Meanwhile, <a href="https://github.com/dotnet/runtime/blob/05671f8e4ac6ee921ca314a189912ddaee22b8f8/src/libraries/System.Private.CoreLib/src/System/Convert.cs#:~:text=public%20static%20int%20ToInt32(bool,%7D">Convert.ToInt32</a> is, currently, written as a ternary (unclear why the benchmark came back slightly better than explicit ternary, but…).</p><p>(FWIW, I changed AggressiveInlining to NoInlining — in case optimizing-JIT somehow can’t honor it— and the unsafe-cast results are not poorer than Convert.ToInt32(). One could also try adding a local bool to consolidate AsInt+NonNormalizedAsInt.)</p><p>Branch-prediction <em>is</em> remarkable (see the once most up-voted question on <a href="https://stackoverflow.com/questions/11227809/why-is-processing-a-sorted-array-faster-than-processing-an-unsorted-array">stackoverflow</a>) when given data that can be predicted. In this <a href="https://en.algorithmica.org/hpc/pipelining/branchless/#when-predication-is-beneficial">algorithmica.org</a> article, they claim looping over if( a[i] &lt; P ) s+= a[ i ] outperforms branchless when P is &lt; ~25% or &gt; ~80%. However, I didn’t observe much sensitivity in AsInt() at 50%, 15% or 80%. (Though I didn’t exhaustively test target-runtimes, framework versions, Roslyn vs RyuJit, etc., only .net 7 on Win11 w/ Intel CPU, so 2nd caveat.)</p><p>In my post on BenchmarkDotNet, I mention how one can measure branch-mispredict rates. If they’re prevalent for you, AsInt() might be applicable for you.</p><p><a href="https://medium.com/@norm.bryar/tips-on-c-benchmarking-c094ed283d7f">Tips on C# Benchmarking. Ideas to maximize your use of… | by Norm Bryar | Medium</a></p><h3>A Few Other Branchless Techniques</h3><p>The classic expression is this:</p><pre>int isTrue = (...some bool expr...).AsInt();<br>int answer = (isTrue * trueCaseVal) + ((1 - isTrue) * falseCaseVal);</pre><p>An isub, two imuls, and an add are traded for a branch. <br>Can this still be faster?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*O0egUQoDUO-4AVrMwVfpKw.png" /><figcaption>Multiply and add speed</figcaption></figure><p>where UnsafeCast() is now doing</p><pre>int bi = boolData[ i ].AsInt();<br>sum += (bi * trueResp) + ((1 - bi) * falseResp);<br><br>// vs the Ternary bechmark<br>sum += boolData[i] ? trueResp : falseResp;</pre><p>A poor-man’s ASCII lower- to upper-case converter might use c -= (char)(32 * ((c &gt;= ‘a’).AsInt() &amp; (c &lt;= ‘z’).AsInt())) in this vein.</p><p>Sign-extension mask tricks also fall into this category, e.g. to get an absolute-value int mask = x &gt;&gt; 31; x = (x ^ mask) — mask; or max() via</p><pre>int BranchlessMax(int val1, int val2)<br>{<br>    int diff = val1 - val2;  // check if val1 &gt; val2<br>    int sign = diff &gt;&gt; 31;   // sign-extend to yield 0 or 0xFFFFFFFF<br>    return a - (diff &amp; sign);  // val1 or (val1 - (val1 - val2)) = val2<br>}</pre><p>Benchmarks for such left to the reader (note many C++ compilers will emit asm using CMOV on seeing max() written as a ternary, so YMMV).</p><h3>What Else Does ‘Unsafe’ Improve?</h3><p>If your component wasn’t already compiled to allow <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/unsafe-code">unsafe </a>code-blocks, would you do so just to unlock this bool.AsInt() trick? Probably not. But if your project is also array-heavy, uses custom hashers, or other critical-path mem-walking logic, unsafe-blocks might be worhtwhile. Here’s a loop-unrolling benchmark to set the mood.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*JHrsO8enBQV4AMA3ddTPRQ.png" /></figure><p>with pointer-unrolled code like so:</p><pre>fixed (int* arr = data) // GC-pin <br>{<br>    int* ptr    = arr;<br>    int* ptrEnd = arr + (8 * (data.Length / 8));<br>    while (ptr &lt; ptrEnd)<br>    {<br>        sum += *(ptr + 0) +    // vs data[i + 0] in normal unroll <br>               *(ptr + 1) +<br>               ...<br>               *(ptr + 7);<br>        ptr += 8;<br>    }<br>    // data.length - end remainder code omitted for brevity</pre><p>First, of course, see if Span&lt;T&gt;, ref return, or other type/scope assured techniques work well enough before resorting to unsafe. Of course.</p><h3>Conclusion</h3><p>If you’re driven to squeeze maximum performance from some routines, .net allows you to use ‘unsafe’ (i.e. not guaranteed the compiler can hold your hand) blocks that might allow branchless programming idioms you’ve missed from other languages like C++. Treating bools as ints may play a role here.</p><p>As always, thanks for reading and leave comments if you’ve got ‘em.</p><h4>Footnotes</h4><p>¹ — C# interops with external sources (DllImport, blitting, …) might hit this.</p><pre>[StructLayout(LayoutKind.Explicit)]<br>public struct ForeignStruct<br>{<br>    [FieldOffset(0)] public int  id;<br>    [FieldOffset(4)] public bool test;<br>}<br>...<br>public unsafe ForeignStruct LoadFromFile()<br>{<br>    ForeignStruct extInput = default;<br>    ((byte*)&amp;extInput)[4] = 0xAA;  // wacky file blitted as-is<br>    return extInput;<br>}<br><br>var x = LoadFromFile();<br>NonNormalizedAsInt(x.test)  // 170 oopse!<br>x.test.AsInt()              // 1 yay! </pre><p>That said, even the deprecated-due-to-security System.Runtime.Serialization.Formatters.Binary.<a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter.deserialize?view=net-7.0#system-runtime-serialization-formatters-binary-binaryformatter-deserialize(system-io-stream)">BinaryFormatter</a> was always smart enough to normalize a byte-stream’s 0xAA to a 1 when assigning to a bool, but be aware if your code has esoteric interops.</p><p>² — Other languages might use double-negation to normalize a bool to {0,1}. In C# !! doesn’t work well, as it’s often compiled-away early: b = !!b is lowered to just b = b.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f541d349fce4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conveying Context with AsyncLocal]]></title>
            <link>https://medium.com/@norm.bryar/conveying-context-with-asynclocal-91fa474a5b42?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/91fa474a5b42</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 02:16:17 GMT</pubDate>
            <atom:updated>2022-12-01T02:16:17.049Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uKLMEh6-2iNLiFEDOyqtEw.jpeg" /></figure><p>Sometimes you want custom, ambient- or cross-cutting-context to flow across multiple components or multiple task continuations. Maybe it’s some <em>ad-hoc</em> TenantId, CorrelationId, vector-clock info, IsTest or IsShadow categorization, A/B test flight ids, remaining latency-budget (e.g. for cache or retry aggressiveness), quality-of-service level (e.g. for throttling perf-SLA’d requests vs. low-priority, re-runnable batch-reqs). Whatever.</p><p>There could be a lot of distance between where the context arrives and where its used, and you likely want to avoid so-called <a href="https://softwareengineering.stackexchange.com/a/335013">Tramp Data</a> (passing data to one routine just so that routine can pass it to another routine), as that’s bad conceptual coupling and quite messy given more context ideas invariably emerge later. What you really want is a way to add the data similarly to how Thread.<a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.currentculture?view=net-7.0">CurrentCulture</a> or .<a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread.currentprincipal?view=net-7.0">CurrentPrincipal</a> make UI and security cross-cutting data ubiquitously available. Those are ‘global’, yet per-request at the same time.</p><h3>AsyncLocal</h3><p>Happily, the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.threading.asynclocal-1?view=net-7.0">AsyncLocal</a> class helps us out a lot here.</p><p>Now, at first glance in the doc page, you’re going to see a static instance and property-setter, and immediately huff that there’s no-way that could be thread-safe. But it is. The property-setter is really acting as a static-method, updating the execution-context that .Net itself uses for flowing state into child tasks no matter which thread(s) they’re scheduled onto. <a href="https://github.com/dotnet/runtime/blob/3b706dd67bd0d5a29a5bf1801e970b94e0d0f33e/src/libraries/System.Private.CoreLib/src/System/Threading/Thread.cs#:~:text=Interlocked.CompareExchange(ref%20s_asyncLocalPrincipal,s_asyncLocalPrincipal.Value%20%3D%20value%3B">CurrentPrincipal</a> and <a href="https://github.com/dotnet/runtime/blob/ce406f10e7e9af7716c037191fa4956ddef70f67/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs#:~:text=new%20AsyncLocal%3CCultureInfo%3E(AsyncLocalSetCurrentCulture,!.Value%20%3D%20value%3B">CurrentCulture</a> use the technique.</p><pre>using System.Threading;<br><br>class Example<br>{<br>    static AsyncLocal&lt;string&gt; _asyncLocalString = new AsyncLocal&lt;string&gt;();<br><br>    static async Task AsyncMethodA()<br>    {<br>        _asyncLocalString.Value = req.TenantId; // 👈 Thread-safe? </pre><p>under the covers <a href="https://github.com/dotnet/runtime/blob/16b6369b7509e58c35431f05681a9f9e5d10afaa/src/libraries/System.Private.CoreLib/src/System/Threading/AsyncLocal.cs#L45">this</a> executes:</p><pre>public T Value<br>{<br> ...<br> set =&gt;<br>     ExecutionContext.SetLocalValue(this, value, _valueChangedHandler != null);</pre><p>Granted, adding hidden-inputs to functions is contrary to purity, but there are certain cases where marshalling some data through the backdoor (ideally to turn it into a passed parameter at a good spot) is the practical choice. Up to you and your team (and your priest or counselor).</p><h3>Bare-Bones AmbientContext Utility</h3><p>Now, we tried to motivate this exploration by saying we have a whole bundle of context-data that we’re likely to add to over time. Dedicated static-members of strongly-typed AsyncLocal&lt;T&gt;, akin to <a href="https://github.com/dotnet/runtime/blob/ce406f10e7e9af7716c037191fa4956ddef70f67/src/libraries/System.Private.CoreLib/src/System/Globalization/CultureInfo.cs#:~:text=private%20static%20AsyncLocal,%3E%3F%20s_asyncLocalCurrentUICulture%3B">CultureInfo’s</a>, is the prudent way to go for most apps, but should you be giving customers a library they can hang context on, a dict of AsyncLocals seems to work.</p><pre>// Utility to set/get ambient context that flows across async tasks<br>public static class AmbientContext<br>{<br>    public static readonly ConcurrentDictionary&lt;string, AsyncLocal&lt;object?&gt;&gt; <br>        _contexts = new(StringComparer.Ordinal);<br>    <br>    public static void Set&lt;T&gt;(string key, [MaybeNull] T val)<br>    {<br>        AsyncLocal&lt;object?&gt; keyctx = _contexts.AddOrUpdate( <br>                key,<br>                k      =&gt; new AsyncLocal&lt;object?&gt;(),<br>                (k,al) =&gt; al);<br>        keyctx.Value = (object?) val;<br>    }<br>    <br>    [return: MaybeNull]<br>    public static T Get&lt;T&gt;(string key)<br>    {<br>       return _contexts.TryGetValue( key, out AsyncLocal&lt;object?&gt;? keyctx)<br>                ? (T) (keyctx!.Value ?? default(T)!)<br>                : default(T);<br>    }<br>}</pre><p>Perhaps your DefaultController could call AmbientContext.Set( TenantIdKey, claims… ) and several layers deeper the data-access-layer calls AmbientContext.Get&lt;string&gt;( TenantIdKey ) to lookup this customer’s storage.</p><p>(Having to supply the type-parameter to Get&lt;T&gt; is a ptential source of bugs, so, again, dedicated fields are desired in most cases. A hybrid with fields and a dict might be advisable.)</p><h4>Scoped State</h4><p>If a method spawns multiple child tasks, those might try to add or override AmbientContexts (e.g. if an ML layer runs two models, live and IsShadow, you could have the ML engine skip billing for the latter context). Changes made by a child percolate to grand-child tasks, but don’t bleed-over into sibling child tasks, nor back into the parent task.</p><p>(Yes, in the naive AmbientContext class above, the ConcurrentDictionary still holds the memory, but the <em>ExceutionContext </em>does not. Pruning keys from this implementation of AmbientContext is inherently dangerous.)</p><p><em>But what if I want to mutate the context?</em> Well, it’s changes to AsyncLocal.Value that have scope isolation. Getting the <em>same</em> Value to a mutable reference object would let you change it.</p><pre>RunStats reqStats = new RunStats { LatencyBudget = 500L, ... };<br>AmbientContext.Set( &quot;RunStats&quot;, reqStats );<br>await DoStuff();<br>if (reqStats.LatencyBudget &lt; 0L) { throw new TimeoutEx(&quot;slow-poke&quot;); }<br><br>...<br><br>Task&lt;X&gt; DoStuff()<br>{<br>    RunStats stats = AmbientContext.Get&lt;RunStats&gt;(&quot;RunStats&quot;);<br>    long msecStart = Environment.TickCount64;<br>    ...<br>    stats.LatencyBudget -= (Environment.TickCount64 - msecStart);  // interlocked ideally<br></pre><h4>Unit-Testing</h4><p>We want our unit-tests to be able to run in parallel. Luckily, this is no different from our web-server running http-requests in parallel: task-schedulers will draw from thread-pools, flowing ExecutionContext either way. Remember to have each UT assign to all AsyncLocal.Value properties they intend to inspect (or if mutable modify) to preserve the isolation.</p><h3>Context Across RPCs / Persistence</h3><p>No doubt you’d want an ability to flow context even over the wire to other micro- or external-services (perhaps on a per-endpoint basis, e.g. CorrelationId to everyone, sometimes as http-header, sometimes as a gRPC field, but QoS level only to some endpoints). We won’t delve deeply into this, but one approach would web-apis might be to use ASP.Net’s <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-6.0">middleware</a> and client-factory <a href="https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-7.0#outgoing-request-middleware">middleware</a> support.</p><pre>using Microsoft.AspNetCore.Builder;<br>IApplicationBuilder builder = ... <br>builder.UseMiddleware&lt;AmbientContextMiddleware&gt;();<br><br>...<br><br>public class AmbientContextMiddleware<br>{<br>    private readonly RequestDelegate _next;<br><br>    public MyMiddleware(RequestDelegate next) =&gt; <br>        _next = next;<br><br>    public async Task Invoke(HttpContext context)<br>    {<br>        string corrId = <br>            context.Request<br>                   .Headers[&quot;x-foocorp-correlationId&quot;]<br>                   .FirstOrDefault( Guid.NewGuid().ToString() );<br>        <br>        AmbientContext.Set( CorrelationIdKey, corrId );<br>        <br>        await _next.Invoke(context);<br><br>        // TODO: emit corrid response header, esp if _we_ created it<br>    }<br>}<br><br>public class OutboundHttpAmbientContext <br>    : System.Net.Http.DelegatingHandler<br>{<br>    protected override Task&lt;HttpResponseMessage&gt; SendAsync(<br>        HttpRequestMessage request,<br>        CancellationToken  cancellationToken)<br>    {<br>        string corrId = AmbientContext.Get&lt;string&gt;(CorrelationIdKey);<br>        if (corrId is not null)<br>        {<br>            request.Headers[&quot;x-foocorp-correlationId&quot;]<br>                   .Append( corrId );<br>        }<br><br>        return base.SendAsync( request, cancellationToken );<br>}</pre><p>Something similar would be desired for persistence to, say, your Data Science training pipeline to capture the TenantId, flight-id(s), etc. from context for them to condition their models on.</p><h3>Conclusion</h3><p>We’ve explored how AsyncLocal can help you convey custom execution-context that can keep your code clean from tramp-data. I hope you’ve found it an interesting technique. As always, leave a comment about your approach or experience with this one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91fa474a5b42" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Doubles or Floats, Let .Net7 Help]]></title>
            <link>https://medium.com/@norm.bryar/doubles-or-floats-let-net7-help-ad30a51cbfb5?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad30a51cbfb5</guid>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Thu, 24 Nov 2022 16:42:19 GMT</pubDate>
            <atom:updated>2022-11-24T16:42:19.974Z</atom:updated>
            <content:encoded><![CDATA[<h3>Doubles or Floats, Let .Net7 Help</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R3xmXIU4wMGTnTvy" /><figcaption>Photo by <a href="https://unsplash.com/@blakewisz?utm_source=medium&amp;utm_medium=referral">Blake Wisz</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Typically, teams needing real numbers reach for 64-bit doubles instinctively, but .Net7 has made it easier to work with 32-bit floats. This might get one wondering <em>what should we ask, or look out for, when straying off familiar, beaten-path?</em></p><p>The C# language has always encouraged doubles: 3.14 is a double, you need a suffix 3.14f to make a float. BCL’s Math.Xxx(...)functions lack overrides for float, e.g Abs(double), so you needed casts (hence conversions) to use them with floats. Even in the 32-bit app era, 64-bit doubles were the orthodox choice. <em>Why risk running out of range, propagating precision-errors, or piling-up conversion costs?</em></p><p>Of course, prior to .Net7, though, there were pockets of specialized types preferring float, e.g. <a href="https://learn.microsoft.com/en-us/dotnet/api/system.numerics.vector3?view=net-6.0">Vector3</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.numerics.quaternion?view=net-6.0">Quaternion</a>, etc. And now with .Net7’s <a href="https://learn.microsoft.com/en-us/dotnet/standard/generics/math">Generic Math</a> interfaces re-implementing the Math.<em>Xxx</em> methods (and more) on more numeric types, float could be worth a second look.</p><pre>float theta          = float.Pi / 4.0f;   <br>var (sinVal, cosVal) = float.SinCos( theta );    👈 whoa, look at that!</pre><p>(Alternatively, there’s theMathF class, but you can access several more type-specific things via the <em>type</em>.<em>extension</em> form, e.g. short.Log2(…))</p><h3>Pros of single-precision float</h3><p>Here’s some reasons to prefer float over double:</p><ol><li>They take up half the memory-space (obviously). <br>Your look-up table of ip-address to lat/lon centroid would suddenly take half the number of gigabytes. What’s not to love?</li><li>Some FPU ops will run faster on smaller types.<br>Transcendentals (trig, sqrt, log/exp) and even division may perform better. Others (fmul/fadd, …) are inherently fast and likely agnostic to size (BTW, try to favor such ops in the inner-loop anyway, e.g. use x,y,z vectors over trig angles,)</li><li>Twice as many values will fit on a cache-line. <br>A time-series float[] would get more L1/L2 cache-hits (and if data must be iteratively revisited, fewer self-evictions).</li><li>…and twice as many values vectorized by SIMD <a href="https://devblogs.microsoft.com/dotnet/hardware-intrinsics-in-net-core/">intrinsics</a>.<br>(If you know of SIMD, you know float/double tradeoffs already, but if you’re <em>What’s a SIMD?</em> it’s via Vector intrinsics that they <a href="https://github.com/dotnet/runtime/pull/64624">massively sped-up</a> Enumerable.Max, <a href="https://devblogs.microsoft.com/dotnet/hardware-intrinsics-in-net-core/#improving-the-perf-by-vectorizing-the-loop">.Sum</a>, .Average, and ML.Net and physics-engines in gaming, etc.)</li></ol><h3>Cons of using float</h3><ol><li>Range is limited: 10³⁸ (vs 10³⁰⁸), though usually not the main concern.</li><li>Precision is limited: The IEEE-754 standard for 32-bit floats gives them a 24 bit significand (64-bit doubles have 53 bits resolution, see <a href="http://evanw.github.io/float-toy/">float-toy</a>). 0.5²⁴ ~= 10^-6 (vs 10^-16) decimal digits of accuracy.<br>Often that suffices. With a small exponent, e.g. 5, we could express a range of latitudes between 32° — 64°, approximately Jacksonville, Florida up past Inukjuak, Quebec. Resolution would be ~0.425 meters, better than GPS <a href="https://www.gps.gov/systems/gps/performance/accuracy/">User Range Error</a> .64m (and likely better by far than your company’s privacy/anonymizer truncation policy ;-)</li></ol><pre>float EarthRadius = 6_378_137.0f;  // meters <br>float midLat = 45.0f;<br>float secLat = float.BitIncrement(midLat);  // significand += 1<br>float DegToRad = (MathF.PI / 180.0f);<br>float res = EarthRadius * (secLat - midLat) * DegToRad; 👈 == 0.4246 </pre><p>Note: precision dilates with scale. Had you used float to store elapsed seconds, say (the unit-choice doesn’t matter much), then after 60s, the resolution is 3.8μs, but after 1hr, 0.24ms, and 1 day, 7.8ms. Large values between 2²⁴ to 2³¹, a 32-bit int will give better precision than float ; a float can store integers exactly up to 2²³, then even integers to 2²⁴ (with rounding jumps, and ++ oper doing nothing), every fourth integer up to 2²⁶, etc.</p><p>(Out of scope for this article, using <a href="https://en.wikipedia.org/wiki/Fixed-point_arithmetic">fixed-point math</a> to counter dilation.)</p><p>Ok, so ensure you’re within constraints of the ‘cons’ and benchmark to check the ‘pros’. <em>Et voila, c’est tout. </em>Right?</p><p>When the math on the data is minimal, I suspect <em>oui, c’est tout</em>, but the more involved the computation, the longer state feeds and changes itself, etc., the more possibility you will see a wrinkle. Try some of the following before reverting your double-to-float PR.</p><h3>Precision and Noise-Propagation</h3><p>The following may surprise folks about floating-point equality.</p><pre>Console.Write(<br>  $&quot;\r\n  0.1 + 0.1 + 0.1 == 0.3 : {(0.1 + 0.1 + 0.1) == 0.3}&quot; + <br>  $&quot;\r\n  123 / 10 * 10 == 123   : {((123 / 10) * 10) == 123}&quot; +<br>  $&quot;\r\n  (double)(float)47.136 == 47.136 : &quot; + <br>                                $&quot;{((double)(float)47.136) == 47.136}&quot; + <br>  $&quot;\r\n  1.1f == 1.1            : {1.1f == 1.1}&quot;);</pre><p>The problem, of course, is due to quantization/rounding noise. Those were _doubles_ and still they failed. It’s because 0.1 is imperfectly expressible, thus quantized, the sum of two quantized 0.1s is then also quantized as is the sum of 0.2 and 0.1, so little wonder a quantized expression of 0.3 doesn’t equate (0.1.ToString(“G17) = “1.00..001”, 0.3.ToString(“G17”) = “2.99999…”).</p><p>Floats will be worse. The last line also shows that even a constant coerced from double to float won’t equal that same constant!</p><p>&lt;aside&gt; And so, my jaw dropped in a code review seeing Dictionary&lt;double, …&gt;. One can just imagine the very poor recall rate, and sky-high memory use from ‘updates’ rarely actually replacing elements. The dev did explain he’d only store consts that were integers, but I still worried new-hire might learn bad ideas.&lt;/aside&gt;</p><h4>Numerical Stability</h4><p>I’m not a numerical-methods guy, so take this with a grain of salt, but … Stable algorithms are crafted to try to attenuate the flow of rounding-errors. Moreover, good algos may even re-arrange the data to perform ops in the least noisy alternative order (e.g. matrix methods re-map rows and columns as they go). Some of those hand-techniques you used in <em>Math 201 — Intro to Linear Algebra</em> actually propagate and amplify noise, <a href="https://www.math.net/cramers-rule">Cramer’s Rule</a> being such a beast.</p><p>A few stability-minded heuristics:</p><ul><li>Subtracting very similar numbers amplifies noise.<br>x.xxxxxx1 — x.xxxxxx0 has rounded both values already, so the answer 1.1E-6 approximates what in reality could be 1.0E-6 or 1.2E-6. Small absolute errors result in a 10% relative error here. This phenomenon is called <a href="https://en.wikipedia.org/wiki/Catastrophic_cancellation">catastrophic cancellation</a> and can get far bigger. The classic way to avoid is to favor adds, multiplies, and divides over subtracts, e.g.</li></ul><pre>// cancel risk minimized by promoting to double, as fsub unavoidable<br>double b4ac = ((double)((b * b)) - (4.0 * a * c));   <br>float  b4ac_sqrt = float.Sqrt( (float) b4ac );<br>float  x1 = -1.0f * <br>            (b + (float.Sign(b) * b4ac_sqrt))<br>            / (2.0f * a);<br>-float  x2 = -1.0f *<br>-            (b - (float.Sign(b) * b4ac_sqrt))   // cancellation risk!<br>-            / (2.0f * a);<br>+float  x2 = c / (a * x1);    // equiv form avoiding subtraction</pre><ul><li>Subtracting very dissimilar numbers can destabilize the result.<br>xxx.xxxxxx — y.yyyyyyE-6 doesn’t remove enough from the larger term. If we want to know what percentage of a wall’s length the player is at, better to temp = wallEnd — player; pct = (wallLen — temp)/wallLen; than to start = wallEnd — wallLen; pct = (player-start)/wallLen; assuming Len is very small compared to the open-world coordinate of End (I’m told some game data starts coords at 2.0E9 to avoid other rendering artifacts, else this example may seem puzzling).</li><li>Recursion should aim to diminish noise per step.<br>For instance, instead of En+1 = 1 — n*En, n = 1,2,3…, which multiplies prior errors by ever larger factors, try going backwards En-1 = (1 — En)/n, n = …3, 2, 1?</li><li>You may have better luck by trying to keep intermediate terms much smaller than the final answer. Converge to the final answer with small corrections.</li></ul><p>Likely good tricks to keep in mind even if stick with doubles. Alas, I don’t think there’s a simple master recipe for stability, but awareness helps.</p><p>I wish I could say checked { … } blocks could help catch overflow problems, but sadly, not in .Net. Peppering float.IsInfinity(res) checks/asserts about may help. (Underflow, e.g. float.Epsilon / 2.0f, results in 0.0f, less convenient to infer a range issue, but happily usually less a show-stopper.) If infinity (overflow) is encountered, one technique might be to pre-scale, incurring more ops, yes, so benchmark to see if the size/cache-line/etc. benefits don’t evaporate. For instance, …</p><pre>-// if the straight-forward sum-of-squares overflows ... <br>-float magSquared = x1*x1 + x2*x2 + ... xn*xn;<br><br>+// Psuedo-code of pre-divide <br>+float scale     = max(x1, x2, ... xn );<br>+float scaleInv2 = 1.0f / (scale * scale);  // fmul is much faster than fdiv<br>+float mag = scale * Math.Sqrt( scaleInv2*x1*x1 + ... + scaleInv2*xn*xn );</pre><p>For cases like computing eigenvalues, matrix-inverse, etc., I’d probably just stick with double (and also use well-established LAPACK-ish libraries, vs. rolling my own “faster” algo, ’cause edge-cases abound and neither I nor my maintaining teammates are specialists). One can still use floats for data-streams, as deltas, etc., and surgically use doubles in critical, deep crunching methods.</p><p>.Net7’s Generic Math however does include a few methods to eliminate some intermediate-result down-conversions. Intel FPUs internally hold 80 bit values, up-converting both double and float to this higher precision, so intrinsics that combine math ops may eliminate down-conversion commonly performed steps, sometimes likely faster, e.g. for <a href="https://en.wikipedia.org/wiki/Multiply%E2%80%93accumulate_operation">multiply-accumulate</a> scenarios perhaps like for <a href="https://en.wikipedia.org/wiki/Horner%27s_method">Horner’s Method</a>, <a href="https://learn.microsoft.com/en-us/dotnet/api/system.mathf.fusedmultiplyadd?view=net-7.0#system-mathf-fusedmultiplyadd(system-single-system-single-system-single)">float.FusedMultiplyAdd(x,y,acc)</a> might be used, or for vector-projections (v1 * v2 / |v1||v2|), <a href="https://learn.microsoft.com/en-us/dotnet/api/system.mathf.reciprocalsqrtestimate?view=net-7.0">float.ReciprocalSqrtEstimate(mag)</a>. Searching the literature, you can also find some compensating algorithms such as <a href="https://en.wikipedia.org/wiki/Kahan_summation_algorithm">Kahan Summation</a>, if error propagation is suspected. <br>(Confession, I’ve never resorted to these, so my guess at example usage may now showcase them well.)</p><p>Often, though, no hunt for accuracy-preserving techiques is needed. <br>Again, awareness can pay dividends, so...</p><h3>Even Smaller Than Float!</h3><p>There’s also a new 16-bit <a href="https://devblogs.microsoft.com/dotnet/introducing-the-half-type/">Half</a> type, a scant 1/4 the size of a double! And in .Net7, it supports a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.half?view=net-7.0">lot of ops</a> on it. At 10 significant bits, I doubt you’ll want to use it for your geospatial logic, but machine-learning folk find a lot of use for this size, e.g. in memory-bound deep-learning. GPUs support this type, and/or a 16-bit cousin, <a href="https://cloud.google.com/blog/products/ai-machine-learning/bfloat16-the-secret-to-high-performance-on-cloud-tpus">BFLOAT16</a> (which I’m unaware of .NET’s plans around), this format that trades 3 bits of significand for wider exponent range. So, clearly, very useful things can still be achieved with limited precision (encouraging for float, no?).</p><h3>Conclusion</h3><p>For big collections or quickly repeated transforms on numeric collections, see if picking float instead of defaulting to use doubles might be a win. We’ve seen a couple contra-indications around range or precision, but more tasks are amenable than you might think. And .Net7 makes using floats easier now than ever. Peeking afresh at the <a href="https://learn.microsoft.com/en-us/dotnet/api/system.numerics?view=net-7.0">System.Numeric</a>s namespace is a good idea regardless.</p><p>Hope you enjoyed the read.</p><h4>Misc Resources</h4><ul><li><a href="https://learn.microsoft.com/en-us/dotnet/api/system.numerics?view=net-7.0">System.Numerics namespace</a></li><li>Grigory Sapunov’s <a href="https://moocaholic.medium.com/fp64-fp32-fp16-bfloat16-tf32-and-other-members-of-the-zoo-a1ca7897d407">FP64 … BFLOAT16… and other members of the ZOO</a></li><li>Bruce Dawson’s excellent series on <a href="https://randomascii.wordpress.com/category/floating-point/">Floating Point</a></li><li><a href="https://floating-point-gui.de/references/">Floating point guide references</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad30a51cbfb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dictionaries and Spans]]></title>
            <link>https://medium.com/@norm.bryar/dictionaries-and-spans-7b72433da75d?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b72433da75d</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Mon, 07 Nov 2022 17:56:42 GMT</pubDate>
            <atom:updated>2022-11-07T17:56:42.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVQUrOAIuBROsd8Hq4Fhlg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@edge2edgemedia?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Edge2Edge Media</a> on <a href="https://unsplash.com/s/photos/jigsaw-puzzle?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I really like .Net’s Span&lt;T&gt;; it wonderfully reduces needless alloc-and-pour operations, making this single innovation the cornerstone of a wealth of perf-improvements in each new version of .Net (née .Net Core). Span-aware APIs are available to all of us, too (e.g. <a href="https://medium.com/@norm.bryar/string-create-and-span-char-165650064fe0">String.Create and Span&lt;char&gt;</a>), so we all look smarter in the aura of the genius .Net team.</p><p>In case you haven’t heard of <a href="https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/">Span&lt;T&gt;</a>, think of it like an abstraction over many sources of memory (heap, stack, marshalled) that you can slide-around atop that memory: A <em>view</em> basically. You can often dodge a bunch of expensive string-splitting/substring operations, by just sliding a span where you want it to point.</p><p>A big block of (semi-)structured text like JSON or CSV should get you wondering “How can I parse this with Spans?” In my case I was wondering “How can I compose a Dictionary of extracted values … without extracting any values?”</p><p>Unfortunately, a Span&lt;T&gt; is a <a href="https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/ref-struct">ref struct</a> and as such doesn’t like to be owned by something GC’able, so can’t be a Dictionary key nor value. However a Memory&lt;T&gt; has no such limitation (though <a href="https://learn.microsoft.com/en-us/dotnet/standard/memory-and-spans/memory-t-usage-guidelines">still has some</a>), and its .Span property gives you access to the highly-nifty Span-centric APIs.</p><h3>Memory as Dictionary-Value</h3><p><em>Well, can you build a </em><em>Dictionary&lt;..., ReadOnlyMemory&lt;char&gt;&gt;?</em> Yes.</p><pre>string text =  <br>        &quot;Lorem ipsum &lt;see cref=\&quot;linkA\&quot;/&gt; dolor yada yada&quot;; </pre><pre>// horrible code follows, but demos getting &quot;linkA&quot; indices<br>int start =     text.IndexOf(&quot;&lt;see cref=\&quot;&quot;, 0); <br>start = start &gt;= 0 ? start + &quot;&lt;see cref=\&quot;&quot;.Length : -1; <br>int end = start &gt;= 0 ? text.IndexOf(&quot;\&quot;/&gt;&quot;, start) : -1; <br> <br>Dictionary&lt;string, ReadOnlyMemory&lt;char&gt;&gt; links = new(); <br>links.Add(&quot;see&quot;, text.AsMemory()[start..end]);</pre><p>Memory&lt;char&gt; holds-on to its source object, so won’t risk outliving it, nonetheless you’re typically going this route because you want to hold-on to the raw text for some reason (e.g. send an RPC , enqueue/persist, …).</p><p>Of course, at some point you’re likely to want the value back out again, like via links[“see”].ToString(), so you’d want to weigh whether anything’s really being gained by ‘scheduling’ that materialization, e.g. temporally-separate phases looking at only subsets of keys (for validation or routing). Conversion-heavy cases like int.Parse(links[“timeout”].Span) could also yield a win this way.</p><p><em>How much a win? </em>First round of testing, I excluded key-names being extracted rather getting re-used from a parsing helper. This test showed no memory used to make dict values (minus the const 624B used in the test-scaffold logic itself)! As expected. Execution times were ~86% (after test-overhead times subtracted from numerator and denominator).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dPKmsxC2_T3gvncMC8Ft2w.png" /></figure><h4>Memory as Dictionary Key</h4><p>Those who feel “if <em>some </em>medicine is good, <em>way more</em> must be <em>way good</em>!” their next idea might be making dictionary-keys themselves late-bound. <br><em>Can you build a </em><em>Dictionary&lt;ReadOnlyMemory&lt;char&gt;, ReadOnlyMemory&lt;char&gt;&gt;? Yes, just a tad more work.</em></p><p>To be used as a key, the type has to support GetHashCode(). At first I was depressed .Net6 Memory extension methods didn’t have that overload (q.v. <a href="https://github.com/dotnet/runtime/issues/50322">issue 50322</a>), but we can easily implement an IEqualityComparer the dictionary will use instead, simply deferring to String.GetHashCode(), etc.</p><pre>MemStringEqualityComparer comp = new(ignoreCase: true);<br>Dictionary&lt;ReadOnlyMemory&lt;char&gt;, ReadOnlyMemory&lt;char&gt;&gt; dict = <br>        new(expectedKeyCount, comp);</pre><pre>...</pre><pre>public class MemStringEqualityComparer :<br>     IEqualityComparer&lt;ReadOnlyMemory&lt;char&gt;&gt;<br>{<br>    private StringComparison _comparison;</pre><pre>    public MemStringEqualityComparer( bool ignoreCase = false ) =&gt;<br>        _comparison = ignoreCase<br>            ? StringComparison.OrdinalIgnoreCase<br>            : StringComparison.Ordinal;</pre><pre>    public int GetHashCode( ReadOnlyMemory&lt;char&gt; obj ) =&gt;<br>        string.GetHashCode( obj.Span, _comparison );</pre><pre>    public bool Equals(<br>        ReadOnlyMemory&lt;char&gt; x, <br>        ReadOnlyMemory&lt;char&gt; y) =&gt;<br>            System.MemoryExtensions.Equals( <br>              x.Span, y.Span, _comparison );<br>}</pre><p>Note: this will use the <a href="https://en.wikipedia.org/wiki/Collision_attack#Hash_flooding">hash-attack-safe</a> <a href="https://learn.microsoft.com/en-us/dotnet/framework/configure-apps/file-schema/runtime/userandomizedstringhashalgorithm-element">randomized-string-hash-algorithm</a>, also making ReadOnlyMemory&lt;char&gt; hashes comparable to a mem.ToString().GetHashCode(_comparison). <br>But you still can’t persist the hash-value, IPC/RPC it, etc. <br>I haven’t looked into whether the non-randomized flavors (e.g. <a href="https://github.com/dotnet/runtime/blob/fb1d318935e57c48e6d018d67b2bade74e020cef/src/libraries/System.Private.CoreLib/src/System/String.Comparison.cs#L853">this</a>) are similarly accessible to us.</p><p><em>Performance using Memory in Key and Value?</em> Happily, pretty good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4BotLB2Df2gQaoqabOLQg.png" /><figcaption>IsKeyConst true =&gt; known at startup, false =&gt; discovered from raw text</figcaption></figure><p>As hoped, allocs with Memory&lt;char&gt; are gone and perf is pretty close.</p><p>If the key-strings are extracted from the corpus (IsKeyConst = False), memory is twice as bad for Dictionary&lt;T,T&gt; when T is string vs keys known <em>a priori (</em>IsKeyConst = True), as expected. But Memory&lt;char&gt; still 0. <br>(Note: the tests’ raw text used a 20-char pattern of featur001:fval001–1;featur002:fval002–1;… with keys and vals same size.)</p><p>Test code <a href="https://dotnetfiddle.net/h4cQah">here</a>.</p><h3>A Toy Use-Case</h3><p>Our hashes over from Memory&lt;char&gt; don’t depend on the raw text instance, making merging dictionaries even in the late-bound (IsKeyConst=false) case safe. For instance, if the use-case is multiple sources of formatted strings with an inherent order-of-precedence and we want to avoid substring ops when there’s a good chance the next source will simply replace the value, it might look like this:</p><pre>Dictionary&lt;..., ...&gt; dict = new(estCt, comparer);<br>for (int s = 4; s &gt;= 1; --s) <br>{ <br>    string? source = s switch <br>    {<br>        4 =&gt; await ReadAllAsync( localSafeDefaultsFile ),<br>        3 =&gt; await ReadAllAsync( environmentFile ),<br>        2 =&gt; await ReadAllAsync( tenantIdFile ),<br>        1 =&gt; GetQueryParameter( flightQp ),<br>    };</pre><pre>    MergeToDictionary( dict, source );<br>}</pre><pre>...</pre><pre>public void MergeToDictionary(<br>    Dictionary&lt;..., ...&gt; dict,<br>    string? txt )<br>{<br>    if (string.IsNullOrWhitespace(txt)<br>        return;</pre><pre>    ReadOnlyMemory&lt;char&gt; txtMem = txt.AsMemory();<br>    int start = 0;<br>    for (;;)<br>    {<br>        var (key, val, next) = GetNextPair( txtMem, start );<br>        if (next &lt; 0)<br>            break;</pre><pre>        AddToDictionary( dict, txt, key, val );</pre><pre>        start = next;<br>    }<br>}</pre><pre>// This same syntax works <br>// whether ... is string or ReadOnlyMemory&lt;char&gt;.<br>internal void AddToDictionary(<br>    Dictionary&lt;..., ...&gt;  dict,<br>    ...                  mem,<br>    Range                key,<br>    Range                val ) =&gt;<br>        dict[ mem[key] ] = mem[val];  </pre><p>I’ll leave to the reader’s imagination the text-walking GetNextPair(…) implementation, but it’s returning the Ranges for where a key and its associated value are found (plus some monotonic progress offset), all achievable with span.(Last)IndexOf(…) / .Trim().</p><h4>Conclusion</h4><p>Span&lt;T&gt; has a cousin, Memory&lt;T&gt; that overcomes the stack-only constraints of span, but readily gives you access to its extension-methods. The heap friendly Memory&lt;T&gt; can even be used in collections, such as Dictionary&lt;…, …&gt;. This might be a viable design-option for you to avoid avoid alloc+pour and GC taxes. Keys take a smidge of work (and you may prefer a simpler <a href="https://medium.com/@norm.bryar/taming-duplicate-strings-364cad5b3ca1">Taming Duplicate Strings</a> interning), but might pay off if the keys are not known at compile-time.</p><p>Hopefully you’ve found this an interesting explore of Memory&lt;T&gt;. Thanks for reading.</p><p><strong>Bonus Material </strong>— ReadOnlyMemory is, surprise, a readonly struct. But its value-slot in the dictionary <em>is</em> writable (just copying over the immutable value <em>en toto</em>). If you wanted to inspect/act-on the value before replacing it, you could use <a href="https://learn.microsoft.com/en-us/dotnet/api/system.runtime.interopservices.collectionsmarshal?view=net-6.0">CollectionsMarshal.GetValueRefOrAddDefault</a>, e.g. …</p><pre>ref ReadOnlyMemory&lt;char&gt; gammaRef = <br>    ref CollectionsMarshal.GetValueRefOrAddDefault( <br>          dict, <br>          myKey, <br>          out bool gotVal);</pre><pre>if (gotVal)  ...perhaps test/act-on gammaRef&#39;s old val... <br>gammaRef = srcMem[valRange];  // Replace it w/o 2nd lookup cost!</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b72433da75d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[String.Create and Span<char>]]></title>
            <link>https://medium.com/@norm.bryar/string-create-and-span-char-165650064fe0?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/165650064fe0</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[net-core]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Sat, 01 Oct 2022 18:57:42 GMT</pubDate>
            <atom:updated>2022-10-01T18:57:42.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abANDe8EH5_dQNySiG6Dqw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Adi Goldstein</a> on <a href="https://unsplash.com/s/photos/track?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Man, I love .Net Core. More particularly, I love the entire shift in focus from the old .Net Framework ship-vehicle-is-windows, closed-source mindset that under-invested in performance improvements, but in Core perf is at the forefront.</p><p>Here’s an interesting example in the age-old problem of string-formatting. I only recently discovered (though it’s been there since Core 2.1) another place where that perf-epiphany Span&lt;T&gt; makes an impact: <a href="https://learn.microsoft.com/en-us/dotnet/api/system.string.create?view=net-6.0#system-string-create-1(system-int32-0-system-buffers-spanaction((system-char-0)))">String.Create&lt;T&gt;(int len, T state, SpanAction&lt;char,T&gt;)</a>.</p><p><em>Why is it cool?</em> Everyone’s had to emit a formatted string at some point, in fact over and over and over we do. The perf-conscious among us seek to do so with a minimum of interim-string allocations and pours (e.g. avoiding long chains of logMsg += &quot;, &quot; + terms[i] in favor of stringBuilder.AppendJoin( “,”, terms), etc.) String.Create takes this a step further.</p><p>With String.Create, as long as you can compute the length up-front, you can supply a callback that’s given access to the final string’s <em>tabula rasa</em> internal char[] via a span. This allows you to write directly into any location in the string’s memory (immutability be damned! ‘cause it’s construction), with no subsequent re-alloc/pour like StringBuilder.ToString() would do. Lowest possible mem-use.</p><p>Be sure to see where you can leverage the TryFormat( Span&lt;char&gt;, … ) method that most object-types support, irradicating per-field, interim string allocs and their mem-copy pours, too.</p><pre>public class Maven <br>{ <br>    public string   Name          { get; set; } <br>    public string?  Motto         { get; set; } <br>    public int      FollowerCount { get; set; } <br>    public DateTime RecentActive  { get; set; } <br> <br>    public override string ToString() <br>    { <br>        const string mottoLabel  = &quot;Motto: &quot;; <br>        const string fctLabel    = &quot;Followers: &quot;; <br>        const string recentLabel = &quot;Recent: &quot;; <br>        const int    fctLen      = 5;  // 9999+ or right-padded ct<br>        const int    recLen      = 10; // 2022/03/25 <br>         <br>        string eol = Environment.NewLine; <br> <br>        int len =  <br>            Name.Length +   <br>            (Motto is not null  <br>              ? eol.Length + mottoLabel.Length + Motto.Length <br>              : 0) +  <br>            (eol.Length + fctLabel.Length    + fctLen) +  <br>            (eol.Length + recentLabel.Length + recLen); <br>         <br>        string result = string.Create(  <br>          len, <br>          this, <br>          (buffer, self) =&gt; <br>          { <br>              Write( self.Name.AsSpan(), ref buffer); <br>               <br>              if (Motto is not null) <br>              { <br>                  Write( eol,        ref buffer ); <br>                  Write( mottoLabel, ref buffer ); <br>                  Write( self.Motto, ref buffer ); <br>              } <br>                             <br>              Write( eol,         ref buffer) ; <br>              Write( fctLabel,    ref buffer ); <br>              Write( self.FollowerCount &gt; 9999 <br>                      ? &quot;9999+&quot; <br>                      : $&quot;{self.FollowerCount,-5:g}&quot;, ref buffer ); <br> <br>              Write( eol,         ref buffer); <br>              Write( recentLabel, ref buffer); <br>              self.RecentActive.TryFormat(  <br>                buffer,  <br>                out int _, <br>                &quot;yyyy/MM/dd&quot;); <br>          }); <br>           <br>        return result; <br>         <br>        // ---  <br>        static void Write( <br>            ReadOnlySpan&lt;char&gt; term, <br>            ref Span&lt;char&gt; buf) <br>        { <br>            term.CopyTo( buf ); <br>            buf = buf.Slice( term.Length ); <br>        } <br>    } <br>}</pre><p>I like to have a utility-function, Write, to automatically advance the span. Pretty readable with that in place. You might want to add other Write overloads could handle DateTime, etc. consistently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/758/1*YMbHLXVQMXbXl9GYurgBzQ.png" /><figcaption>Ta-dah!</figcaption></figure><p>Above I kind’a cheated by forcing the format of numbers and dates instead of using a culturally-aware formatting, and I required a left-justified padding on the FollowerCount that ultimately takes a little more space than needed plus incurs an interpolated-string alloc. <em>Tsk, tsk.</em> You grasp the basics, though.</p><p>Note: if your length calculation is too big, you’ll have trailing (char)0 elements that may render poorly. Too small, the string will be silently truncated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*rlb2hrrzLDzNcXpSlz0O7Q.png" /><figcaption>LINQPad output if I over-estimated length value</figcaption></figure><p>The TState arg will typically hold the object you want string-formatted, allowing the callback to be static, sans closures, thus fast as can be. There might be interesting cases, though, where the callback’s state param holds supporting information (culture?) as a tuple of the subject being formatted, or you’re ok with the closure cost, or …</p><p>I really should have used String.Create in the <a href="https://medium.com/@norm.bryar/leveraging-exception-data-4abccaa277c0">Leveraging Exception.Data</a> story’s ToStringEx().</p><p>Anyway, enjoy!</p><p>— — — — — —</p><p><em>Aside:</em> if you’re still needing to use StringBuilder in many places, you might at least want to consider putting them in a pool for re-use of their scratch buffer memory. See the <a href="https://learn.microsoft.com/en-us/aspnet/core/performance/objectpool?view=aspnetcore-6.0#objectpool-sample">Object reuse with Object Pool</a> MSDN topic for an example.</p><p><em>Another aside:</em> before this, our team wrote our own stack-based string-builder, gist of which below. It still requires a pour to get the final string, so we’ll likely be migrating to String.Create on touching those callers later.</p><pre>public ref struct StackStringBuilder<br>{<br>    private readonly Span&lt;char&gt; buffer;</pre><pre>    public StackStringBuilder( Span&lt;char&gt; buf ) =&gt; buffer = buf;</pre><pre>    public int Length { get; private set; } = 0;</pre><pre>    public void Append( int x )<br>    {<br>        Span&lt;char&gt; temp = stackalloc char[ IntMaxLen ];<br>        x.TryFormat( temp, out int xlen );<br>        temp.Slice( 0, xlen )<br>            .CopyTo( this.buffer.Slice( this.Length ) );<br>        this.Length += xlen;<br>    }</pre><pre>    ... more Append overloads ... </pre><pre>    public string ToString() =&gt; <br>        new string( this.buffer[ 0..this.Length ] );<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165650064fe0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tips on C# Benchmarking]]></title>
            <link>https://medium.com/@norm.bryar/tips-on-c-benchmarking-c094ed283d7f?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/c094ed283d7f</guid>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Tue, 16 Aug 2022 05:28:39 GMT</pubDate>
            <atom:updated>2022-08-16T06:02:38.338Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*Uol0bZvvOlStgNYk" /><figcaption>Photo by <a href="https://unsplash.com/@diana_pole?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Diana Polekhina</a> on <a href="https://unsplash.com/s/photos/tape-measure?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Here are some miscellaneous thoughts on maximizing your use of <a href="https://benchmarkdotnet.org/">BenchmarkDotNet</a>. You’ve likely used, or seen used, this <a href="https://www.nuget.org/packages/BenchmarkDotNet/">NuGet package</a> already; it’s prominent in Microsoft’s own blogs <a href="https://devblogs.microsoft.com/dotnet/performance-improvements-in-net-6/">[1]</a> <a href="https://devblogs.microsoft.com/dotnet/performance-improvements-in-aspnet-core-6/">[2]</a> <a href="https://docs.microsoft.com/en-us/ef/core/performance/performance-diagnosis?tabs=simple-logging%2Cload-entities#benchmarking-with-ef-core">[3]</a> about the performance improvements in each version of .Net Core, and in multiple others’ blogs. To get serious about perf comparisons in .Net, you need to know this tool (and you probably do).</p><p>There are, however, a couple of more nuanced behaviors, and a pitfall or two, you’ll find worth your while to consider.</p><h3>Accuracy Tips</h3><h4>Ensure The Routine’s Really Doing the Work</h4><p>You may have once compared some MethodA vs. MethodB, scratching your head, asking “how can the difference be <em>so </em>drastic?”</p><p>We developers are fickle how we regard the optimizer (compiler-lowering, MSIL-generation or JIT). We often write crap-code of duplicated expressions, assuming the optimizer will intelligently hoist loop-invariants, enregister redundant call results, etc. Yet we sometimes write benchmarks assuming the optimizer will unintelligently leave our silly efficiencies alone.</p><p>Once, a friend went to measure string’soperator+ vs StringBuilder, only they used string-literals. The compiler will recognize “foo” + “bar” can be replaced by “foobar” at compile-time, then the optimizer will realize you’re never using “foobar” and skip even that (“dead-code elimination” this is called). Naturally, it then appeared to him as if string operator+ is orders of magnitude faster than StringBuilder.Append() … which thankfully he knew couldn’t be true and we looked into it together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*yvwR_dKXWqvItem2t7hqlA.png" /></figure><p>Mistakes of this form are <em>not </em>uncommon. I only wish they were rare. I bet you’ve seen a couple such mistaken-miracles in blogs yourself.</p><p><strong>Action Item:</strong> Use SharpLab.io’s Results: ‘JIT Asm’ in Release mode or <a href="https://www.linqpad.net/">LINQPad</a>’s IL+Native result-tab (shown above, with #LINQPad optimize+) to see what your benchmark method is <em>actually </em>doing. Has the optimizer out-foxed the benchmark author?</p><p><strong>Tips:</strong></p><ol><li>Give the function an output (touched inside the loop, if you’re using one), to ensure intended calculations are preserved. E.g. int sum; for (int i=0; i&lt;N; ++i) { sum += … } return sum; <br>But <strong>don’t</strong> store the result in a collection or un-bounded concatenated string (see below).</li><li>Consider adorning the benchmark class with the [ReturnValueValidator] attribute so that each Benchmark method’s return value must agree. <br>Fast, but wrong, is … well, wrong.</li><li>Avoid constants in the test method. For instance, make a loop upper-bound a non-const (member) variable so the JIT’r won’t unroll the loop (which it may decide to if the body is uncomplicated), as otherwise different loop-overheads spoil your comparisons. And we’ve already mentioned the compiler pre-calculates literal/constant expressions, so 2 * 6 will not test imul speed, it’s 12 before the test even starts. This so-called ‘convolution of constants’ can be quite clever, so just use member-vars instead.</li><li>Adorn helper routines with [MethodImpl(MethodImplOptions.NoInlining)] to ensure the optimizer didn’t inline the helper in one method but in another method decline to do so. The helper’s effect is biased if the overhead of its call was eliminated in one case but not the other.</li><li>Can’t avoid setup-steps within the benchmark-method (vs. a [GlobalSetup])? You may be able to reduce the impact of it by repeating the actual work statement (e.g. copy it inline 20 times) then [Benchmark(OperationsPerInvoke = 20)] will report the work time plus only 1/20th of the inline setup time.</li></ol><h4>Tiered-JITing Effects</h4><p>It turns out the Just-In-Time (JIT) MSIL-to-native conversion is not a one-and-done process. The first pass is focused on app load-time, so skimps on optimization. Later, if the system sees a method is wildly popular, it will decide to re-JIT that method with more aggressive optimizations.</p><p><em>Why is this notable for benchmarking?</em> Because BenchmarkDotNet can’t distinguish between re-JIT’s memory-costs and your method’s (at least last I checked w/ .net5 also BMDN <a href="https://github.com/dotnet/BenchmarkDotNet/issues/1542">issue 1542&#39;s</a> still open), so if it seems your routine and its dependencies use surprising amounts of memory, be skeptical and re-measure with lighter load. (Re-JIT happily — or aggravatingly — sometimes manifests as sporadic high-mem reports.)</p><p><strong>Tips:</strong></p><ol><li>Seeing sporadic memory jumps? Maybe you’re running too many inputs in the benchmark, e.g. reduce your 64MB input block to 128KB and see if mem-use becomes consistent again.</li><li>Don’t explicitly skip the warmup-phase (e.g. RunStrategy.ColdStart). Hopefully if a re-optimization is going to occur, you can coax it to happen during warmup. (Be aware also if your test uses any caches, they may also be fully-populated after warmup. C.f. <em>IterationSetup</em> below).</li></ol><h4>Reducing Noise</h4><p>You want to avoid uncontrolled or non-stationary sources of variation.</p><p>Tip:</p><ol><li>Make more deterministic stubs for any I/Os: RPCs, file-operations, etc.<br>(Anecdotally, I believe how you make these stubs matter; I’ve seen benchmarks given Moq lambdas where output .netstat files had a lot of mock-related activity making one distrust the answer. A real, hand-crafted stub implementation-class seems safer to me.)</li><li>Don’t have the benchmark method adding to collections that might grow without bounds. OutOfMemory issues aside, growth policies that double the buffer and pour contents will dominate within your results. More generally, just don’t allow side-effects.</li><li>Don’t have a lot of other apps running while the benchmark runs. CPU quanta may be given to fetching your emails, throwing off your timings.<br>(Especially not on an un-plugged laptop, whose high-temp/high-fan or battery-level transition may incite reduced-clock mode.)</li><li>Don’t have the benchmark method itself alter the inputs for the next iteration. Use [IterationSetup]/[IterationCleanup], (with the caveat that it might be applied every N ~= 16 iterations, see <a href="https://github.com/dotnet/BenchmarkDotNet/issues/730">issue 730</a>). I haven’t played with [ArgumentsSource] or ValuesGenerator, but they might help you. I try to stick with just [GlobalSetup].</li><li>Aim for repeatable runs, e.g. if you do use Random, give it a fixed seed: static Random _rand = new(1234); Repeatability is esp. important for benchmarks within your Continuous Integration test-gates where you might be failing builds (and pissing off devs) on phantom perf-regressions.</li></ol><p>Human nature gravitates to focusing on a single, low-mental-effort number, e.g. the <strong>Mean</strong> column. But you should also examine your test-results for high variance, multi-modal distributions, or outliers. <em>Why?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*5I92nWi2Yzb4iLgNLgGtYw.png" /><figcaption>from Matt Warren’s <strong>Performance is a Feature</strong> on Slideshare.net</figcaption></figure><p>The <em>MValue </em>comes from <a href="https://www.brendangregg.com/FrequencyTrails/modes.html">Brendan Gregg’s algorithm</a> for expressing the degree of modality in the frequency distribution (e.g. if latency seems to cluster around many discrete peaks). An mvalue above 2, to me, warrants a closer look. Adding the [MValueColumn] (<a href="https://benchmarkdotnet.org/articles/samples/IntroMultimodal.html">example here</a>) attribute emits this scalar to the main results table (which is often the only output people look at or will paste in docs).</p><p>My run of BiModal =&gt; Multimodal(2); where int MultiModal(int n) { Thread.Sleeep( (_rand.Next(n) + 1) * 100 ); return n; } yielded this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4RjAxu2cFG7bUfj50MGtUQ.png" /></figure><p>Seeing the (big red warning, of course, but also) high MValue, you’d want to scroll upwards to find the histogram and summary-stats for the method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*2E-c7QNfQazfselLguR9jg.png" /></figure><p>While it looks like we have 4 discrete modes above, actual execution has 2 modes. (Sadly, I’m not sure how you’d tweak the offsets/resolution to avoid the <a href="https://aakinshin.net/posts/misleading-histograms/">misleading histogram</a>, but I assume it is possible given Andrey Akinshin also wrote BMDN’s stats lib. If you find out how, please tell me in the ‘Comments’). Anyway, weird shapes beg questions: Why modes arose? Will production code see the same inputs as the benchmark? Might even further outliers exist? Etc.</p><h3>Why I Love LINQPad (with a grain of salt)</h3><p>I highly encourage people to run more benchmarks. I’ve actually made a LINQPad <a href="https://forum.linqpad.net/discussion/287/custom-snippets">code-snippet</a> to quickly create my favorite configs, which allows me to compare two approaches on a whim. You get interesting insights when experiments are easy.</p><p>Such a LINQPad benchmark run can be stood-up so fast, I often do so during Code Reviews to suggest a faster or lower-mem option.</p><p>Easy test crafting even helps avoid over-engineering: It allowed me to see the cross-over point below which a linear List scan beats a Dictionary, or below which string operator+ <em>is</em> faster than StringBuilder.</p><p>Perf can follow the Pareto principal: 80% of the cost from 20% of the code. Sometimes 2–3 degrees deep (80% of 80% = 64%, due to 20% * 20% =4% of code). And it can be easier to tear apart the code in LINQPad (vs. refactoring for SOLID you’d do in master).</p><p>LINQPad hosting goes a little smoother with the [InProcess] attribute. But seems to fail with some analyzers, e.g [EtwProfiler], [HardwareCounter]. I also doubt it fits the <em>eliminate sources of variability</em> criteria for maximizing stability and trust (worse, I admit sometimes I’m on a laptop). The InProcess attribute, in particular, hampers isolation, thus leaving memory measures, etc. open to some noise. But overall, I feel this is often a good first step.</p><h3>Additional Diagnosers</h3><p>While [MemoryDiagnoser] is something I almost always add, you might like to have other diagnosers in your tool-chest, such as cpu-counter based ones. Take the case of branch-predictions. The <a href="https://everything2.com/title/Branch+Target+Buffer">BTB</a> is great when it works, but pipeline stalls are pretty bad when branches are mis-predicted, such as when the data is random (or even if data is consistent <em>intra-</em>request, but 2+ opposite concurent requests start confusing branch-prediction).</p><p>Here’s an example showing branch [HardwareCounters(…)]:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jKKOCHl_cKUU3k8hJ9mzsA.png" /></figure><p>from the following code:</p><pre>[ShortRunJob][ReturnValueValidator]<br>[HardwareCounters(<br>    HardwareCounter.BranchMispredictions,<br>    HardwareCounter.BranchInstructions)]<br>public class BranchBenchmarks<br>{<br>  [Benchmark(Baseline= true)]<br>  public int IfStatements() {<br>    int  wordCt = 0;<br>    bool inWord = false;<br>    bool inPrev = false;<br>    foreach (char ch in input) {<br>        inPrev = inWord;</pre><pre>        // Lowercase first as most chars are lower<br>        // Some sentances, names have an uppercase<br>        // our test never has digits, but ... <br>        inWord = ((ch &gt;= &#39;a&#39;) &amp;&amp; (ch &lt;= &#39;z&#39;)) ||<br>                 ((ch &gt;= &#39;A&#39;) &amp;&amp; (ch &lt;= &#39;Z&#39;)) ||<br>                 ((ch &gt;= &#39;0&#39;) &amp;&amp; (ch &lt;= &#39;9&#39;));<br>        if (inWord &amp;&amp; !inPrev) {<br>            wordCt++;<br>        }<br>    }<br>    return wordCt;<br>  }</pre><pre>  [Benchmark]<br>  public int Branchless() {<br>    int wordCt = 0;<br>    int inWord = 0;<br>    int inPrev = 0;<br>    foreach (char ch in input) {<br>        inPrev = inWord;</pre><pre>        // Use look-up table instead of bool tests.<br>        inWord = inwordMask[ (int) ch ];</pre><pre>        // Use bit-wise AND to set increment-amount.<br>        wordCt += inWord &amp; (inPrev ^ 1);<br>    }<br>    return wordCt;<br>  }</pre><pre>  private static readonly string input =<br>    @&quot;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt  ... &quot; // elided for brevity, 69 words<br>  <br>  private static readonly int[] inwordMask =<br>        Enumerable.Range(0,255)<br>                  .Select( x =&gt; (char) x switch {<br>                           &#39; &#39;  =&gt; 0,<br>                           &#39;\r&#39; =&gt; 0,<br>                           &#39;\n&#39; =&gt; 0,<br>                           _    =&gt; 1,<br>                          })<br>                  .ToArray();<br>}</pre><p>Add the BenchmarkDotNet.Diagnostics.Windows NuGet and run in an elevated (Administrator) console, and we can look at many cpu-counters.</p><p>(I don’t recommend you combine this with OperationsPerInvoke=… as the branch*/op columns’ integer output may round to zero and be misleading.)</p><p>If you add any additonal diagnosers, these will be excluded from the all-sacred timing-run. The remaining diagnosers get lumped together into a second run. So your overall benchmark is slower, but 2+ non-timing diagnosers pay the same cost (with those I checked) so might still be ok to add a few to your CI-build’s benchmarks.</p><h3>Conclusion</h3><p>Using BenchmarkDotNet is remarkably easy, and removes pitfalls that a naïve, roll-your-own-with-Stopwatch attempt would subject you to, and it has a wide variety of knobs for testing a myriad of target platforms. You can use it for comparisons of alternative implementations, or for drill-down/profiling of a single method, or for guardrails within a CI system. While easy to use, it’s still true the more you know the better it gets, and hopefully one or two of the details above helps you make a test get better. I definitely recommend taking a look at the excellent references below.</p><p>Thanks for reading.</p><h4>References</h4><ul><li><a href="https://github.com/dotnet/performance/blob/main/docs/microbenchmark-design-guidelines.md">performance/microbenchmark-design-guidelines.md at main · dotnet/performance (github.com)</a></li><li>Andrey Akinshin’s <a href="https://www.bing.com/videos/search?q=Andrey+Akinshin&amp;view=detail&amp;mid=1D0B78C39041323258051D0B78C3904132325805&amp;FORM=VIRE">Performance Testing at Dotnetos 2019</a> conference.<br>and <a href="https://www.amazon.com/Pro-NET-Benchmarking-Performance-Measurement-ebook/dp/B07TP275JT/ref=sr_1_1">Pro .Net Benchmarking</a> book.</li><li><a href="https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md">performance/benchmarkdotnet.md at main · dotnet/performance (github.com)</a></li><li><a href="https://aakinshin.net/posts/stephen-toub-benchmarks-part1/">Measuring Performance Improvements in .NET Core with BenchmarkDotNet (Part 1) | Andrey Akinshin (aakinshin.net)</a></li><li><a href="https://wojciechnagorski.com/2020/04/cross-platform-profiling-.net-code-with-benchmarkdotnet/">https://wojciechnagorski.com/2020/04/cross-platform-profiling-.net-code-with-benchmarkdotnet/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c094ed283d7f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Embrace the Nullable Reference]]></title>
            <link>https://medium.com/@norm.bryar/embrace-the-nullable-reference-95759737cdda?source=rss-4f1150f0dd91------2</link>
            <guid isPermaLink="false">https://medium.com/p/95759737cdda</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Norm Bryar]]></dc:creator>
            <pubDate>Wed, 20 Jul 2022 06:27:03 GMT</pubDate>
            <atom:updated>2022-07-20T06:27:03.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ivlk_UWipocx3POuUVDilw.jpeg" /></figure><p>Since C#8, we’ve been able to get compile-time insights about when a reference-type variable might be null. As classes abound in C#, this analyzer feature is a fantastic boon. A <a href="https://www.bing.com/search?q=c%23+nullable+reference+types+best+practices">myriad of articles</a> describe it. Perhaps you’ve even read Mads Torgerson’s original <a href="https://devblogs.microsoft.com/dotnet/embracing-nullable-reference-types/">Embracing Nullable Reference Types</a>. (I wanted to call my article ‘<em>Just Embrace Nullable References Already, Jeez</em>’, but opted for less aggression.)</p><p><em>Do we need yet another article?</em> I wept in a code-review seeing the following in a .csproj. So, … apparently, we do.</p><p>&lt;! — &lt;Nullable&gt;enable&lt;/Nullable&gt; --&gt;</p><p><em>Why? Why?!? </em>A few possibilities came to mind:</p><p>a) Confusion about interoperability.<br>b) Fear of massive overhaul needed on existing components. <br>c) Unawareness of hint-attributes for reducing noise.<br>d) Lack of patterns for common scenarios.<br>e) ‘Warnings Crutch’ fear.</p><h3>Interop?</h3><p>One typically declares a variable to be a nullable by suffixing the type with a ‘?’. Person you cannot be null, Person? roommate might be null. (This is a nicely consistent syntax, even w/ pre-existing language features like <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators#null-conditional-operators--and-">null-conditional</a> ?. and System.Nullable&lt;<a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types">value-type</a>&gt;.)</p><pre>public class Program<br>{<br>    public string WhoIs( Person? whom ) <br>        =&gt; whom?.FirstName ?? &quot;&lt;null&gt;&quot;;<br>}</pre><p>The compiler ‘lowers’ the Person? arg this way:</p><pre>public string WhoIs(<br>  [System.Runtime.CompilerServices.Nullable(2)] Person whom)<br>{<br>    return ((whom != null) ? whom.FirstName : null) ?? &quot;&lt;null&gt;&quot;;<br>}</pre><p>(via <a href="http://sharplab.io/">http://sharplab.io</a>, a tool a Nick Chapsas YouTube vid turned me on to.)</p><p>From our WhoIs(…) lowering, you’ll be delighted to learn Person? is not a distinct type, rather it’s a plain Person type with an attribute applied to the argument. Methods/delegates/lambdas resolve agnostic of the ‘?’. This seems consistent with the CS0111 error one gets trying to overload method F(string) with an F(string?).</p><p>(Sharplab.io further implies the the Nullable attribute itself is compiler-generated, which, if so, I guess could help downlevel clients consume your NuGet or something)</p><pre>namespace System.Runtime.CompilerServices<br>{<br>    [CompilerGenerated]<br>    [Microsoft.CodeAnalysis.Embedded]<br> ...<br>    internal sealed class NullableAttribute : Attribute<br>    { ... }</pre><p>(Maarten Balliauw peeked a bit at the attrib flags <a href="https://blog.maartenballiauw.be/post/2022/04/19/internals-of-csharp-nullable-reference-types-migrating-to-nullable-reference-types-part-2.html">here</a>)</p><p><em>Over-the-wire?</em> If you add nullability to existing an existing POCO (plain-old-C#-object), System.Text.Json or Newtsonsoft will emit the same JSON as before. No back-compat breaking change to your customers/partners/workflows. The de-serializer also works the same (and we’ll touch more on how to fine-tune the compiler-warnings later)</p><p>So, the interop excuse is put to rest!</p><h3>Massive Overhaul?</h3><p>Assemblies A-Sapien referencing B-Troglodyte referencing C-Sapien (nullable-aware, -oblivious, and -aware respectively) can call (2nd-degree) dependencies just fine. The question now is how hard is it to update B-Troglodyte.csproj to &lt;Nullable&gt;enable&lt;/Nullable&gt;?</p><p>Try just that change. Count the warnings and where they occur. Then attack the files in steps (e.g. sorted by git churn-rate or fan-in or something). Particular files can be adorned with #nullable disable (or regions within the file bracketed by #nullable restore or #nullable enable) until you’re able to tackle them. (You can also <em>a la carte,</em> e.g. annotations on but warnings off, etc. … but the potential for confusion seems unattractive to me.)</p><p>Make a policy in your org that <strong>all new files</strong> have nullable-references enabled (via .csproj’s setting or explicit directive like above). As a target-of-opportunity, devs should shrink #nullable disable’s scope on each file edit.</p><p>I believe generated-code, by default, ignores the csproj’s settings; so don’t forget you may need to write your generator to emit #nullable enable.</p><p>So, the massive-overhaul can be smoothed out with directives.</p><h3>Distracting Noise?</h3><p><em>What about noisy false-positives?</em> For starters, you do have the null-forgiving operator, given by the ‘!’ suffix. Once applied, if the var isn’t re-assigned later, everything below treats the null as having been checked-for. It works on expressions, too.</p><pre>private string? GetIfOdd(int i)  =&gt; (i % 2)==1 ? &quot;hi&quot; : null;<br>private string? GetIfEven(int i) =&gt; (i % 2)==0 ? &quot;hi&quot; : null;<br>...</pre><pre>// We know one of the two calls must yield a good instance.<br>string msg = (GetIfOdd(n) ?? GetIfEven(n))!;</pre><p>But the analyzer’s taking our word for it at this point. Better if we can express this more declaratively and move the knowledge to toward the source, inspect-ably correct and encapsulated.</p><p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/attributes/nullable-analysis">Nullability-attributes</a> tell the analyzer how nulls flow. This improves the signal-to-noise ratio for all clients of your code and makes it more self-describing (which appeals to even the ‘<em>comments-are-misleading</em>’ crowd.)</p><pre>[return: NotNullWhenNotNull(&quot;input&quot;)]<br>public string? Normalize( string? input ) { ... }</pre><pre>public bool TryGet(<br>  string key, <br>  [NotNullWhen(true)] out Thingie? thingie) { ... }</pre><pre>[AllowNull]<br>public string Category<br>{<br>    get =&gt; _category;<br>    set =&gt; _category = (value ?? &quot;General&quot;);<br>} </pre><pre>public Do([NotNull] ref T val) { ... }</pre><p>Above, we claim Normalize yields an instance if input was one. In the second example, the NotNullWhen better clarified the out thingieas will be an instance if TryGet returns true. In the third, the setter will accept a null (because the code re-interprets this as a safe default), but the getter will never return null to you. Lastly, val might have been passed-in as null, but points to an instance on Do’s return.</p><p>Attributes come in especially handy for clarifying generic type-parameters, for which the ‘?’ suffix (oddly) doesn’t really work correctly. The MaybeNull… attribs seem especially apt for generic-types, but others apply too.</p><pre>public class Wrapper&lt;T&gt;<br>{<br>    [DisallowNull] public T Value { get; set; }<br>}</pre><pre>... </pre><pre>Wrapper&lt;string&gt; wstr = new() { Value = null };  // warning CS8625<br>Wrapper&lt;int&gt; wi      = new() { Value = ...  };  // still works</pre><p>Or even better to apply <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/where-generic-type-constraint">generic-constraints</a>, e.g. class Wrapper&lt;T&gt; where T : notnull {...} or where T: class?</p><p>Of course there’s still all the tricks you already knew how to use: Method() ?? “some safe default”; a discard case switch { …, _ =&gt; fallbackExpr} or case null: ... etc.</p><p>Finally, of course, <a href="https://docs.microsoft.com/en-us/dotnet/fundamentals/code-analysis/configuration-files">.editorconfig</a> can dial-down the nullability severity on a per-project basis, too. But I find no one ever dials ’em back up again, instead piling on new issues that should have gotten protections.</p><p>So, reduce noise with well-doc’d mechanisms above.</p><h3>Patterns?</h3><h4>The Deserializer Problem</h4><p>One dilemma I’ve seen is with data-transfer objects, which are typically populated by de-serialization (from an RPC, a data-stream, etc.). The dev wants to say some fields always have objects, but faces warnings none are initialized (null), but if they change to string?, etc., it’s not expressing the real expectation.</p><p><em>Just init in the ctor?</em> Some deserializers manage to skip calling the default-ctor (e.g. via <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.runtimehelpers.getuninitializedobject?view=net-6.0">RuntimeHelpers.GetUnitializedObject(Type)</a> or <a href="https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatterservices.getuninitializedobject?view=net-6.0">FormatterServices</a>)! It’s also not assured all possible serializer NuGets you may find will honor the <a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.requiredattribute?view=net-6.0">DataAnnotations.Required</a> attribute.</p><p>Happily, an attribute could help you if you wished to add an IsValid method to your POCO.</p><pre>public class MyPoco<br>{<br>    public string? Alpha { get; set; }<br>    public string? Beta  { get; set; }<br>    public string? Gamma { get; set; }  // really is optional</pre><pre>    [MemberNotNullWhen(true, nameof(Alpha)),<br>     MemberNotNullWhen(true, nameof(Beta))]<br>    public bool IsValid <br>        =&gt; Alpha is not null &amp;&amp; Beta is not null;<br>}<br>...</pre><pre>MyPoco deserialized = SomeBespokeDeserializer&lt;MyPoco&gt;(...);</pre><pre>if (!deserialized.IsValid) throw ... <br>string notNullValue = deserialized.Alpha;  // no warning</pre><p>Yes, awareness that IsValid was called won’t flow deeper into the callstack; you’d have to repeat the IsValid call each time. (Memoizing its result would be overkill unless you also do way more validation work than null-checks.)</p><p>I’m loathe to suggest this, but know many people who’ve used it: you can null-forgive null itself, e.g public string PrimaryKey { get; set; } = null!; to get around the CS8618 warning. Then it’s a gilt-edge priority to have some equivalent of IsValid/throw story… lest your lies catch up to you … from the live-site pager going off.</p><h4>Init Property Pattern</h4><p>Devs seem to love <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer">object-initializer</a> syntax over constructor parameters. Callers might skip a required-property though. You can provide twin ctors.</p><pre>public class Foo<br>{<br>    public Foo()         =&gt; RequiredField = string.Empty;<br>    public Foo(string f) =&gt; RequiredField = f;</pre><pre>    public string  RequiredField { get; init; }<br>    public string? OptionalField { get; init; }<br>}<br>...<br>Foo myFoo = <br>    new Foo(&quot;required-val&quot;)<br>    {<br>        OptionalField = &quot;optional-val&quot;,<br>    };</pre><p>While we could have done public string RequiredField { get; init; } = string.Empty; it executes before any ctor or the init list, so will incur a (negligible) wasted assignment if the caller makes one. (I don’t like to just leave it to the optimizer to figure-out that’s skippable, even if confident the ctor should be inlined.)</p><h3>Warnings Crutch?</h3><p>Someone might claim over-reliance on nullable-ref warnings could lull some dev into a false sense of security to skip param validation. For public classes’ public methods (potentially called from nullable-oblivious assemblies or with a mistaken null-forgiving stringFromInternet!), you should maintain diligence. Declare <em>don’t expect me to like null</em> and then don’t: <br>public DoIt( Foo f ) { f ??= throw new ArgumentNullException...</p><p>All the other use-cases — return-values, out-params, fields within classes — are much more self-describing meanwhile.</p><p>So ‘warnings-crutch’ is a bad metaphor, try ‘flashlight’.</p><h3>Conclusion</h3><p>Should you or your team have had mixed/ambivalent emotions about adopting nullable-references, hopefully seeing some techniques re-entices you to the idea. And if you see a code-review deleting &lt;Nullable&gt; from a csproj, you’ll feel emboldened to ask “why?” And “what have you tried?”</p><p>Do share your thoughts and any patterns you think devs should apply to help their use of nullables go more smoothly. And thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95759737cdda" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>