String (1). The string is immutable because the string has no variability, and when we give a string variable, the value of the string is still present in the heap, but the point address in the stack is changed. This time, there is a problem, if we need to do a lot of assignment to a string, In this case, there will be a lot of useless garbage in memory.
When the program finishes, the GC scans the entire memory, and if the space is not pointed out, it will destroy the space.
(2). We can consider a string as a read-only group of type char.
namespace _07.字符串的第二个特性
{
class Program
{
static void Main(string[] args)
{
//可以将string类型看成char类型的一个只读数组
string s = "abcdefg";
//既然可以将string看做char类型的只读数组,所以我们可以通过下标去访问字符串中的某一个元素
char c1 = s[0];
Console.WriteLine(c1); //获得了a
//s[0] = ‘b‘; 不能这样做因为是只读的
//如果我们非要改变第一个元素的值为‘b‘怎么办呢?
//首先我们要将字符串转换成char数组
char [] C2 = char [ s length
for (int i = 0; i < s.Length; i++)
{
c2[i] = s[i];
}
//然后我们再修改第一个元素
c2[0] = ‘b‘;
//最后我们在将这个字符数组转换成字符串
//string s2 = ""; 频繁的给一个字符串变量赋值由于字符串的不可变性,会产生大量的内存垃圾
StringBuilder s2=new StringBuilder(); //使用StringBuilder频繁的接受赋值就不会产生垃圾
for (int i = 0; i < c2.Length; i++)
{
s2.Append(c2[i]);
}
string s3 = s2.ToString(); //最后再转换成string类型
Console.WriteLine(s3);
Console.ReadKey();
}
}
}
The function of the StringBuilder class uses the StringBuilder class, produces the object, carries on the constant assignment not to produce many memory rubbish, commissions the efficiency of the operation
Verify: Without using StringBuilder:
namespace _08.StringBuilder的使用
{
class Program
{
static void Main(string[] args)
{
string str = null;
Stopwatch sw = new Stopwatch(); //用来测试代码执行的时间
sw.Start(); //开始计时
for (int i = 0; i < 100000; i++)
{
str += i;
}
sw.Stop();
Console.WriteLine(str);
Console.WriteLine(sw.Elapsed); //获取代码运行的时间
Console.ReadKey();
}
}
}
Time consuming: about 14 seconds
We now use Stringbulider to verify:
namespace _08.StringBuilder的使用
{
class Program
{
static void Main(string[] args)
{
string str = null;
StringBuilder sb = new StringBuilder();
Stopwatch sw = new Stopwatch(); //用来测试代码执行的时间
sw.Start(); //开始计时
for (int i = 0; i < 100000; i++)
{
sb.Append(i);
}
sw.Stop();
str = sb.ToString();
Console.WriteLine(str);
Console.WriteLine(sw.Elapsed); //获取代码运行的时间
Console.ReadKey();
}
}
}
Elapsed time: Only 0.1 milliseconds of use
From for notes (Wiz)
04. Immutability of Strings