C#面試題(String和StringBuilder區別)

1.String和StringBuilder區別java

這是java面試題嗎?第一次遇到這種面試題,查閱了一下MSDN,以下。面試

String字符串是不可變,執行的字符串操做例程重複添加或刪除操做到看起來是單個字符串能夠精確顯著的性能損失。 例如,下面的代碼使用的隨機數生成器使用 1000年個字符,範圍從 0x0001 到 0x052F 中建立一個字符串。 儘管代碼會使用字符串串聯以將新字符追加到名爲的現有字符串str,它實際建立一個新String爲每一個串聯操做的對象。dom

using System; using System.IO; using System.Text; public class Example { public static void Main() { Random rnd = new Random(); string str = String.Empty; StreamWriter sw = new StreamWriter(@".\StringFile.txt", false, Encoding.Unicode); for (int ctr = 0; ctr <= 1000; ctr++) { str += Convert.ToChar(rnd.Next(1, 0x0530)); if (str.Length % 60 == 0) str += Environment.NewLine; } sw.Write(str); sw.Close(); } }

 

你可使用StringBuilder類而不是String類用於對字符串的值進行多個更改的操做。 與實例的不一樣String類,StringBuilder是可變的對象; 當你鏈接、 追加或刪除從字符串的子字符串,在單個字符串上執行的操做。 完成後修改的值StringBuilder對象,能夠調用其StringBuilder.ToString方法將其轉換爲字符串。 下面的示例替換String在前面的示例可用於鏈接到從 0x0001 到與 0x052F 的範圍內的 1000 個隨機字符StringBuilder對象。性能

 
      
using System; using System.IO; using System.Text; public class Example { public static void Main() { Random rnd = new Random(); StringBuilder sb = new StringBuilder(); StreamWriter sw = new StreamWriter(@".\StringFile.txt", false, Encoding.Unicode); for (int ctr = 0; ctr <= 1000; ctr++) { sb.Append(Convert.ToChar(rnd.Next(1, 0x0530))); if (sb.Length % 60 == 0) sb.AppendLine(); } sw.Write(sb.ToString()); sw.Close(); } }
相關文章
相關標籤/搜索