Analysis of the differences between string and StingBuilder memory in C
- 2020-10-23 21:12:14
- OfStack
This article analyzes the memory differences between string and StingBuilder in C#, which is helpful to better grasp the usage of string and StingBuilder in C# programming. Share to everybody for everybody reference. The specific methods are as follows:
The difference between string and StringBuilder refer to MSDN. This article programmatically demonstrates how they differ in memory, and therefore in their behavior.
Take a look at this code first:
// Example: string Memory model of
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string a = "1234";
string b = a;//a,and b point to the same address
Console.WriteLine(a);
Console.WriteLine(b);
a = "5678";
Console.WriteLine(a);
Console.WriteLine(b);//That b's value is not changed means string's value cann't be changed
Console.ReadKey();
}
}
}
Output:
1234
1234
5678;change a's value,b's value is not changed
1234
// Example: StringBuilder Memory model of
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
StringBuilder a = new StringBuilder("1234");
StringBuilder b = new StringBuilder();
b = a;
a.Clear();
a.Append("5678");
Console.WriteLine(a);
Console.WriteLine(b);
Console.ReadKey();
}
}
}
Output:
5678
5678
Hopefully this article has helped you with your C# programming.