04.字符串的不可变性

字符串
(1).字符串的不可变性
1047912-20161105102333424-2102146059.png
 因为字符串具有不可以变性,当我们给一个字符串变量,重新赋值的时候,
字符串原来的值还存在于堆中,只是栈中的指向地址改变了.
这个时候,有一个问题,如果我们需要对一个字符串进行大量的赋值操作,
这样的话内存中就会存在很多无用的垃圾.

当程序结束的时候,GC扫描整个内存,如果发现空间没有被指向.就会销毁这个
空间.

1047912-20161105102333736-208145969.png
1047912-20161105102334174-1598563891.png
 (2).我们可以将字符串看做是char类型的一个只读数组.
 
 
   
  1. namespace _07.字符串的第二个特性
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. //可以将string类型看成char类型的一个只读数组
  8. string s = "abcdefg";
  9. //既然可以将string看做char类型的只读数组,所以我们可以通过下标去访问字符串中的某一个元素
  10. char c1 = s[0];
  11. Console.WriteLine(c1); //获得了a
  12. //s[0] = 'b'; 不能这样做因为是只读的
  13. //如果我们非要改变第一个元素的值为'b'怎么办呢?
  14. //首先我们要将字符串转换成char数组
  15. char[] c2 = new char[s.Length];
  16. for (int i = 0; i < s.Length; i++)
  17. {
  18. c2[i] = s[i];
  19. }
  20. //然后我们再修改第一个元素
  21. c2[0] = 'b';
  22. //最后我们在将这个字符数组转换成字符串
  23. //string s2 = ""; 频繁的给一个字符串变量赋值由于字符串的不可变性,会产生大量的内存垃圾
  24. StringBuilder s2=new StringBuilder(); //使用StringBuilder频繁的接受赋值就不会产生垃圾
  25. for (int i = 0; i < c2.Length; i++)
  26. {
  27. s2.Append(c2[i]);
  28. }
  29. string s3 = s2.ToString(); //最后再转换成string类型
  30. Console.WriteLine(s3);
  31. Console.ReadKey();
  32. }
  33. }
  34. }
1047912-20161105102334877-15624061.png

StringBuilder类的作用
使用StringBuilder类,产生的对象,进行不停的赋值就不会产生很多的内存垃圾,
提成了运行效率


验证:
在不使用stringBuilder的情况下:
 
    
  1. namespace _08.StringBuilder的使用
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. string str = null;
  8. Stopwatch sw = new Stopwatch(); //用来测试代码执行的时间
  9. sw.Start(); //开始计时
  10. for (int i = 0; i < 100000; i++)
  11. {
  12. str += i;
  13. }
  14. sw.Stop();
  15. Console.WriteLine(str);
  16. Console.WriteLine(sw.Elapsed); //获取代码运行的时间
  17. Console.ReadKey();
  18. }
  19. }
  20. }
 耗费时间:
1047912-20161105102335190-71372296.png    大约有14秒


我们现在使用StringBulider来验证:
 
   
  1. namespace _08.StringBuilder的使用
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. string str = null;
  8. StringBuilder sb = new StringBuilder();
  9. Stopwatch sw = new Stopwatch(); //用来测试代码执行的时间
  10. sw.Start(); //开始计时
  11. for (int i = 0; i < 100000; i++)
  12. {
  13. sb.Append(i);
  14. }
  15. sw.Stop();
  16. str = sb.ToString();
  17. Console.WriteLine(str);
  18. Console.WriteLine(sw.Elapsed); //获取代码运行的时间
  19. Console.ReadKey();
  20. }
  21. }
  22. }
消耗时间:
仅仅使用了0.1毫秒
1047912-20161105102335440-1841045786.png
 
 




转载于:https://www.cnblogs.com/HelloZyjS/p/6032502.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值