Benchmarks

Benchmarks

as a .NET developer , most of the time I have gotten stuck in my routine works like solving bugs or writings new modules but I have decided to allocate specific time every week and search and code new features of .NET. also i want to benchmark every subject that is important but it has had less issue in the apps that i have developed.

    <PackageReference Include="BenchmarkDotNet" Version="0.14.0" />        
  <TargetFramework>net9.0</TargetFramework>        

1) string concatenation with StringBuilder

I have written many programs that I had to use string concatenation but because of the size of those programs, it was not a big deal to concatenate strings in simple method with just using + operator or using StringBuilder object. but I have studied many articles about the benefits of StringBuilder especially memory usage. so, I designed a simple benchmark to concatenate 1000 words with different length and compared the memory usage and execution time.

This is my simple benchmark code:

MemoryDiagnoser(true)]
[MaxIterationCount(2000)]
[InvocationCount(100)]
[WarmupCount(100)]
public class BenchmarkStringBuilder{
    string[] words;
    public BenchmarkStringBuilder(){
        words=File.ReadAllLines(@"D:\Projects\TestParamCollection\Tests\Resources\Words.txt");
    }

    [Benchmark]
    public bool CreateParagraphSimple(){
        string para="";
        for(int i=0;i<words.Length;i++)
        {
                para+=" "+words[i];
        }

        return true;
    }

      [Benchmark]
    public bool CreateParagraphWithStringBuilder(){
        StringBuilder para=new StringBuilder();
        for(int i=0;i<words.Length;i++)
        {
             para.Append(" "+words[i]);
        }

        return true;
    }
}        

Result:


It is completely obvious that using StringBuilder is so better especially when we want to concatenate huge number of words.

CreateParagraphSimple

  • Mean: 668.63 microseconds (us)
  • Error: 13.337 us
  • StdDev: 132.776 us (fairly high, meaning the execution time varies more than the second method)
  • Median: 599.79 us
  • Gen0: 4210 collections, meaning it created many short-lived objects.
  • Allocated: 6473.82 KB of memory.

CreateParagraphWithStringBuilder

  • Mean: 20.96 us (significantly faster)
  • Error: 0.414 us
  • StdDev: 3.245 us (very low, showing consistent execution time)
  • Median: 19.76 us
  • Gen0: Only 30 collections, meaning fewer short-lived objects.
  • Allocated: 53.57 KB of memory (much less than the simple method).

Explanation:

  • Performance: The CreateParagraphWithStringBuilder method is dramatically faster than the CreateParagraphSimple method. It takes about 30 times less time on average to execute.
  • Memory Allocation: The method using StringBuilder uses far less memory (53.57 KB vs. 6473.82 KB), which indicates that CreateParagraphSimple is likely creating many temporary string objects.
  • Garbage Collection: The simple method triggered 4210 garbage collections in Gen0 compared to just 30 for the StringBuilder method. This is because string concatenation in C# creates new strings in memory each time, while StringBuilder works in place, reducing the need for temporary objects and thus minimizing garbage collection.

CreateParagraphSimple

  • String Immutability: Strings in C# are immutable, meaning each time you concatenate a string (para += ...), a new string is created, and the previous string is discarded. This causes a lot of memory allocations.
  • Memory Consumption: Every iteration creates a new string, which leads to high memory usage and frequent garbage collections. The discarded strings are eventually cleaned up by the garbage collector, but this slows down performance.
  • Time Complexity: The time complexity of repeated string concatenation grows as O(n^2) because with each iteration, a new string is created, and the previous content is copied over.

CreateParagraphWithStringBuilder

  • StringBuilder Efficiency: StringBuilder is designed to handle cases where strings are frequently modified or concatenated. It maintains an internal buffer that can be resized as needed, but it avoids creating new string objects in every iteration.
  • Reduced Memory Allocations: Since StringBuilder operates on its internal buffer, fewer memory allocations are required, leading to better memory efficiency and fewer garbage collections.
  • Time Complexity: The time complexity is O(n) because StringBuilder does not need to recreate the entire string each time; it appends the new data to the existing buffer.

Conclusion:

  • StringBuilder is much more efficient for scenarios involving multiple string concatenations. The large difference in both time and memory shows that StringBuilder avoids the overhead of creating and discarding multiple immutable string objects, making it a better choice for performance-sensitive code, especially when working with large or numerous strings.

要查看或添加评论,请登录

Navid Abedi的更多文章

  • Compare .NET8 vs Go

    Compare .NET8 vs Go

    it has been a while, I am eager to learn go language. I have heard several things about its performance and simplicity.

  • NextJs Deploy On Windows Server

    NextJs Deploy On Windows Server

    In our company, we started using the NextJs framework five years ago to develop websites. However, due to a lack of…

    2 条评论
  • Essential HTTP Security Headers

    Essential HTTP Security Headers

    One of my colleagues sent me a video about the analyzing the security of websites in LinkedIn. I did the same analyze…

  • client-server screen sharing with gRPC

    client-server screen sharing with gRPC

    GitHub: RemoteDeskropApp-gRPC In my previous article about , I introduced a solution for exploring the implementation…

    1 条评论
  • What is Google.Protobuf?

    What is Google.Protobuf?

    This week, I was searching for different protocols about sending and receiving data between client and server. as a…

  • Performance Showdown: EF Core vs. Minimal APIs for SQL Server Record Insertion

    Performance Showdown: EF Core vs. Minimal APIs for SQL Server Record Insertion

    EF Core Entity Framework Core (EF Core) is an open-source, lightweight, and extensible version of the Entity Framework,…

社区洞察

其他会员也浏览了