zoukankan      html  css  js  c++  java
  • C# StringBuilder和String浅析

    C#语言还是比较常见的东西,这里我们主要介绍C# StringBuilder和String,包括介绍大量字符串拼接或频繁对某一字符串进行操作时最好使用 StringBuilder,不要使用 String等方面。

    C# StringBuilder和String区别

    String 在进行运算时(如赋值、拼接等)会产生一个新的实例,而 StringBuilder 则不会。所以在大量字符串拼接或频繁对某一字符串进行操作时最好使用 StringBuilder,不要使用 String

    另外,对于StringBuilder和String我们不得不多说几句:

    1.它是引用类型,在堆上分配内存

    2.运算时会产生一个新的实例

    3.String 对象一旦生成不可改变(Immutable)

    4.定义相等运算符(== 和 !=)是为了比较 String 对象(而不是引用)的值

    C# StringBuilder和String示例:

    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.Text;  
    4.    
    5. namespace Example22  
    6. {  
    7. class Program  
    8. {  
    9. static void Main(string[] args)  
    10. {  
    11. const int cycle = 10000;  
    12.    
    13. long vTickCount = Environment.TickCount;  
    14. String str = null;  
    15. for (int i = 0; i < cycle; i++)  
    16. str += i.ToString();  
    17. Console.WriteLine("String: {0} MSEL", Environment.TickCount - vTickCount);  
    18.    
    19. vTickCount = Environment.TickCount;  
    20. //看到这个变量名我就生气,奇怪为什么大家都使它呢? :)  
    21. StringBuilder sb = new StringBuilder();  
    22. for (int i = 0; i < cycle; i++)  
    23. sb.Append(i);  
    24. Console.WriteLine("StringBuilder: {0} MSEL", Environment.TickCount - vTickCount);  
    25.    
    26. string tmpStr1 = "A";  
    27. string tmpStr2 = tmpStr1;  
    28. Console.WriteLine(tmpStr1);  
    29. Console.WriteLine(tmpStr2);  
    30. //注意后面的输出结果,tmpStr1的值改变并未影响到tmpStr2的值  
    31. tmpStr1 = "B";  
    32. Console.WriteLine(tmpStr1);  
    33. Console.WriteLine(tmpStr2);  
    34.    
    35. Console.ReadLine();  
    36. }  
    37. }  
    38. }
  • 相关阅读:
    react学习笔记4
    php学习笔记
    react学习笔记2
    react学习笔记
    获取一个数组中的随机值
    添加数据库补丁
    $.post $.getScript
    SQLServer2008将表数据导出的方法
    DataTable筛选符合条件的DataRow
    c# 下拉多选的实现
  • 原文地址:https://www.cnblogs.com/qfb620/p/1771535.html
Copyright © 2011-2022 走看看