Boosting Performance and Memory Efficiency: Introducing ToDelimitedString() with Source Generators in Spargine

In programming, it’s very common to convert a collection of words into a delimited string, with commas often used to separate each element. The example below illustrates this using a StringBuilder:

var sb = new StringBuilder();

foreach (var item in words)
{
    if (sb.Length > 0)
    {
        _ = sb.Append(ControlChars.Comma);
    }

    _ = sb.Append($"{item.Key}: {item.Value}"
                  .ToString(CultureInfo.CurrentCulture));
}

return sb.ToString();

In Spargine, I introduced a method called ToDelimitedString() in FastStringBuilder to encapsulate this functionality as an extension method. Let’s examine its performance.

Benchmark Results

The benchmark tests reveal that ToDelimitedString() is 1.23 times more performant and allocates less memory. This improvement in performance is achieved by leveraging a source generator.

Allocations: Normal: 1,320 – 120,768 bytes, ToDelmitedString(): 200 – 48, 728 bytes.

Pick up any books by David McCarter by going to Amazon.com: http://bit.ly/RockYourCodeBooks

One-Time
Monthly
Yearly

Make a one-time donation

Make a monthly donation

Make a yearly donation

Choose an amount

$5.00
$15.00
$100.00
$5.00
$15.00
$100.00
$5.00
$15.00
$100.00

Or enter a custom amount

$

Your contribution is appreciated.

Your contribution is appreciated.

Your contribution is appreciated.

DonateDonate monthlyDonate yearly

If you liked this article, please buy David a cup of Coffee by going here: https://www.buymeacoffee.com/dotnetdave

© The information in this article is copywritten and cannot be reproduced in any way without express permission from David McCarter.


Discover more from dotNetTips.com

Subscribe to get the latest posts sent to your email.

Leave a Reply