using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StringFormatEfficiency { class Program { static void Main(string[] args) { string format = "my {0} is {1}"; string name = "name"; string zhangyaolin = "zhangyaolin"; string my = "my "; string iss = " is "; DateTime start = new DateTime(); DateTime end = new DateTime(); string aa = null; int maxcount = 10e6; for (int ii = 0; ii < 10; ii++) { start = DateTime.Now; for (int i = 0; i < maxcount; i++) { aa = string.Format(format, name, iss); } end = DateTime.Now; TimeSpan ts1 = end - start; Console.WriteLine(ts1.Milliseconds.ToString()); //------------------------- start = DateTime.Now; for (int i = 0; i < maxcount; i++) { aa = string.Concat(my, name, iss, zhangyaolin); } end = DateTime.Now; TimeSpan ts2 = end - start; Console.WriteLine(ts2.Milliseconds.ToString()); //-------------------------- start = DateTime.Now; for (int i = 0; i < maxcount; i++) { aa = my + name + iss + zhangyaolin; } end = DateTime.Now; TimeSpan ts3 = end - start; Console.WriteLine(ts3.Milliseconds.ToString()); Console.WriteLine("time1(format) : time2(connect) : time3(operator) = {0} : {1} : 1", (1.0 * ts1.Milliseconds / ts3.Milliseconds).ToString(“F3”), (1.0 * ts2.Milliseconds / ts3.Milliseconds).ToString(“F3”)); Console.WriteLine(); } } } }
测试结果: