Tuesday, 25 June 2024

String Builder Vs String

String v/s String Builder

This Article Provide following details 

  • What is String Builder
  • Strigbuilder vs string
  • What is the need of text modifications in real time application development
  • Stringbuilder inbuilt functions and usage

Prove Following 

  1. Pragmatically Prove string is immutable .
  2. Execution time difference between string and stringbuilder
  3. Memory Usage difference between string and stringbuilder

What is String and string builder ?

In C#, both string and StringBuilder are used to handle text, but they are designed for different scenarios and have distinct characteristics. Here’s a detailed comparison:

The string type is immutable in C#, so we cannot change its content after its creation. This means that if we create a string type object and try to amend it, it will create a new instance of the object in the memory. And if we alter the string a lot of times, it can cause some performance problems.

 

StringBuilder solves this problem, because, unlike string, it can dynamically expand its memory to support any manipulation of its contents




In C#, both string and StringBuilder are used to handle text, they are designed for same purpose, but using it for different scenarios and have distinct characteristics.

Action

String

Stringbuilder

initialization

string name=”ASP4UT”;

Stringbuilder sb=new stringbuilder(“ASP4UT”);

concatenation

name=name+”Tutorial”;

Sb.Append(“Tutorial”);

Format

String.Format(“Name {0} Age {1}”,”Srinivas”,30)

Sb.AppenFormat("Name : {0} Salary {0:C}", Srinivas,157);

Replace

Name.Replace(“oldVal”,”NewVal”)

Sb.Replace(“oldVal”,”NewVal”)


string Characteristics

string objects are immutable, meaning once a string object is created, it cannot be changed.

Any modification to  a string actually creates a new string object, which can lead to performance overhead, especially in loops or repeated concatenations.

Frequent modifications of string objects can lead to high memory usage due to the creation of many temporary objects.


string str = "Hello";
str += " World";                             // Creates a new string object
str += " Welcome";                       // Creates a new string object
str=”Welcome to ASP4UT”;         // Creates a new string object

Note :- here 1 initialization and 3 modifications so to 4 objects are created for str variable.

Console.WriteLine(str);  // Output: Welcome to ASP4UT

StringBuilder Characteristics

StringBuilder objects are mutable, meaning they can be modified without creating new objects. This makes StringBuilder more efficient for repeated modifications, such as loops or concatenating a large number of strings.

StringBuilder reduces memory overhead by minimizing the creation of temporary objects. It maintains an internal buffer to accommodate changes, which can grow as needed.



StringBuilder sb = new StringBuilder("Hello");
sb.Append(" World");                         //modify same object
sb.Append(" Welcome To");               //modify same object
sb.Append(" ASP4UT");                   //modify same object

Note :- here while use new operator 1 object created and for every modification or append same object will get update. 

Console.WriteLine(sb.ToString());      // Output: Hello World Welcome To ASP4UT

Comparison

·  string: Ideal for simple and less frequent string operations.

·  StringBuilder: Ideal for complex and frequent string modifications, especially within loops.


String

·  Thread Safety:

  • Immutable objects like string are inherently thread-safe, as their state cannot be modified after creation.

·  Memory Usage:

  • Frequent modifications of string objects can lead to high memory usage due to the creation of many temporary objects.

·  Ease of Use:

  • string provides a rich set of methods and operators for easy manipulation and comparison of text.


stringbuilder

Capacity Management:

  • StringBuilder has a Capacity property that can be used to pre-allocate memory to avoid frequent resizing.

Thread Safety:

  • StringBuilder is not thread-safe. If a StringBuilder instance is to be used by multiple threads, proper synchronization is required.

Memory Usage:

  • StringBuilder reduces memory overhead by minimizing the creation of temporary objects. It maintains an internal buffer to accommodate changes, which can grow as needed.

Comparison Summary

Feature

string

StringBuilder

Mutability

Immutable

Mutable

Performance

Slower for frequent modifications

Faster for frequent modifications

Memory Usage

Higher due to creation of new objects

Lower due to in-place modifications

Thread Safety

Inherently thread-safe

Not thread-safe

Use Case

Simple, infrequent string manipulations

Complex, frequent string manipulations


Reason why string modification required? 

String value concatenation is a fundamental operation in programming and is needed in nearly every project for various reasons. Here are some key reasons why string concatenation is essential:

  •        Building Dynamic Content:
  •        Generating HTML and XML:
  •        Formatting Output:
  •        Query Construction:
  •        File Paths and URLs:
  •        Data Serialization:
  •        Template Rendering:
  •       Configuration Files:
  •        Command Construction:
  •        User Input Handling:

Concatenating user input with predefined text to form complete messages or commands.

Example: userMessage = "User " + userName + " has logged in".



String builder Inbuilt function to manipulate text.

 

StringBuilder sb = new StringBuilder()

Append()

sb.Append("I hope you learned something.");

Append New string value to existing value.

AppendLine()

sb.AppendLine();

Add Line break or line of string value

AppendFormat()

sb.AppendFormat("Name : {0} Salary {0:C}", Srinivas,157);

Append Formated sting to existing

Insert

 

var stringBuilder = new StringBuilder("Hi");

stringBuilder.Insert(2, ", welcome to our blog");

 Insert new value on specific index

Replace

 

sb.Replace("learned", "gained");

Replace specific value with new value

Remove

stringBuilder.Remove(0,8);

Remove text from o index to 8 index

Clear 

 

sb.Clear();

Clear current value


When to use string ?

When you don’t require much string concatenation statements go with string.

 

When to use string builder ?

When you required to concatenate string multiple times in your program go with string builder

 example more than 10 time required to concatenate (not sure this time I will give clear metric )

 

what is the benefit of using string builder compare with string

string builder save execution time memory usage when multiple time concatenate string values.



Program to check  string Crete new object on every modification


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace TestAppNetFrameWork
{
    internal class Program
    {
        unsafe static void Main()
        {

            string myString = "Hello, World!";
            fixed (char* strPointer = myString)
            {
                Console.WriteLine($"Value : {0} Address of myString: {(long)strPointer}", myString);
            }

            for (int i = 0; i < 5; i++)
            {
                myString = myString + i;

                fixed (char* strPointer1 = myString)
                {
                    Console.WriteLine($"Value Changed to : {myString} Address of myString: {(long)strPointer1}",myString);
                }
            }


            Console.WriteLine();
            Console.WriteLine();


            int myInt = 42;
            int* intPointer = &myInt;

            Console.WriteLine($"Int Value {myInt} Address of myInt: {(long)intPointer}");
            for (int i = 0; i < 5; i++)
            {
                myInt = myInt + i;
                int* intPointer2 = &myInt;

                Console.WriteLine($"Int Value Changed {myInt} Address of myInt: {(long)intPointer2}");
            }


        }
    }
}




Program to check Execution Time Difference Between string and stringbuilder


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace TestAppNetFrameWork
{
    internal class Program
    {
        static void Main()
        {
            const int iterations = 1000000;
            string resultString = "";
            StringBuilder resultStringBuilder = new StringBuilder();

            // Measure time for string concatenation
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();
            for (int i = 0; i < iterations; i++)
            {
                resultString += "Hello";
            }
            stopwatch.Stop();
            Console.WriteLine($"Time taken for string concatenation: {stopwatch.ElapsedMilliseconds} ms");

            // Measure time for StringBuilder concatenation
            stopwatch.Reset();
            stopwatch.Start();
            for (int i = 0; i < iterations; i++)
            {
                resultStringBuilder.Append("Hello");
            }
            stopwatch.Stop();
            Console.WriteLine($"Time taken for StringBuilder concatenation: {stopwatch.ElapsedMilliseconds} ms");
        }
    }
}


 

String vs Stringbuilder execution time difference 
 

No of Iterations

String execution time

Stringbuilder execution time

1 time concatenation

0 ms

0 ms

10 time concatenation

0 ms

0 ms

100 time concatenation

0 ms

0 ms

1000 time concatenation

2 ms

0 ms

10000 time concatenation

39 ms

0 ms

100000 time concatenation

9892 ms

0 ms

1000000 time concatenation

 Waited for ½ hour no result

10 ms

200000 time concatenation

56534 ms

1 ms

500000

Taking long time

6 ms

5000000

Taking long time

106 ms

 

 

Program to check Memory Usage Difference Between string and stringbuilder


using System.Text;

using BenchmarkDotNet.Attributes;

using BenchmarkDotNet.Configs;

using BenchmarkDotNet.Running;

using BenchmarkDotNet.Diagnosers;


namespace StringConcatenationBenchmark

{

    [MemoryDiagnoser]

    public class ConcatenationBenchmarks

    {

        private const int Iterations = 10000;

        private const string appendString = "Hello";


        [Benchmark]

        public void StringBuilderBenchmark()

        {

            StringBuilder sb = new StringBuilder("Hello");

            for (int i = 0; i < Iterations; i++)

            {

                sb.Append(appendString);

            }

        }


        [Benchmark]

        public void StringBenchmark()

        {

            string str = "Hello";

            for (int i = 0; i < Iterations; i++)

            {

                str += appendString;

            }

        }

    }


    class Program

    {

        static void Main(string[] args)

        {

            var config = ManualConfig.Create(DefaultConfig.Instance)

                .WithOption(ConfigOptions.DisableOptimizationsValidator, true)

                .AddDiagnoser(MemoryDiagnoser.Default);


            var summary = BenchmarkRunner.Run<ConcatenationBenchmarks>(config);

        }

    }

}



String vs Stringbuilder memory consumption difference
 

No of time concate

String memory consumption

Stringbuilder memory consumption

Iterations = 10000;

488588.48 KB

110.88 KB

Iterations = 100000;

4,88,34,895.16 KB

989.81 KB

Iterations = 100;

51.73 KB

1.42 KB

Iterations = 10

768 B

344 B

Iterations = 5;

240 B

208 B

Iterations = 2;

48 B

104 B

Iterations = 0;

0

104 B

 


Iterations = 10000;

 




Iterations = 100000;

 


 


Iterations = 10; 

 


 



Iterations = 5; 

 





Iterations = 2; 

 






Iterations = 0; 

 


 



When Should We Use StringBuilder?

We should use the StringBuilder class when:

·        We expect a lot of operations on a string

·        We need to perform a lot of search operations (StringBuilder doesn’t have the Contains()IndexOf(), or StartsWith() methods)

·        There’s an indefinite number of operations (e.g., using a while loop)

On the other hand, if we have to perform a few operations or a fixed number of operations on a string literal, we’ll be better off using the plain old String class.



---------------------------------------------------------------------------------------

                  below topics     Update Soon 

---------------------------------------------------------------------------------------

  • Reduce StringBuilder allocations using a reusable pool in C#
  • Extract strings using Substring vs. Append in C#
  • Join strings using String.Join vs. StringBuilder.AppendJoin in C#
















No comments:

Post a Comment

Thanks for the contribution, our team will check and reply back if response required.