这些情况使用StringBuilder代替String(抄袭加翻译)

    技术2022-05-20  39

    String和StringBuilder的不同:

    It belongs to String namespace

    It belongs to String. Text namespace

    String object is immutable

    StringBuilder object is mutable

    Assigning:

    String s= "something important";

    Assigning:

    StringBuilder sbuild= new StringBuilder("something important");

    We can use '+' operator or Concat method to concatenate the strings.

    Here we are using Append method.

    When string concatenation happens, additional memory will be allocated.

    Here additional memory will be allocated when the string buffer capacity exceeds only.

     

    对于时间关键的程序在以下情况使用StringBuilder代替String:

    If the number of appends is unknown. (要连接的字符串数量不知道) If appending is on string variables instead of string literals. (连接的是String对象而不是字符串) If string concatenation is in loops. (字符串的连接在循环中) Concatenating string objects returned by multiple methods.(连接被多个方法返回的String对象)

    (from :http://www.c-sharpcorner.com/UploadFile/satisharveti/codeperpart108252009063227AM/codeperpart1.aspx)

    (from: http://www.c-sharpcorner.com/UploadFile/jitendra1987/4169/)

    static void Main(string[] args) { DateTime dt = DateTime.Now; string testString = ""; for (int i = 0; i < 10000; i++) { testString += "test"; } Console.WriteLine("String Performance Test: " + Math.Round(DateTime.Now.Subtract(dt).TotalSeconds,2) + " Seconds : " + Math.Round(DateTime.Now.Subtract(dt).TotalMilliseconds,2) + " Milliseconds"); dt = DateTime.Now; StringBuilder testSBuilder = new StringBuilder(); for (int i = 0; i < 10000; i++) { testSBuilder.Append("test"); } Console.WriteLine("StringBuilder Performance Test: " + Math.Round(DateTime.Now.Subtract(dt).TotalSeconds,2) + " Seconds : " + Math.Round(DateTime.Now.Subtract(dt).TotalMilliseconds,2) + " Milliseconds"); Console.ReadLine(); }

     


    最新回复(0)