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(); } } }}
Test results:
531109125time1 (Format): time2 (CONNECT): time3 (operator) = 4.248: 0.872: 1 5311091_time1 (Format): time2 (CONNECT): time3 (operator) = 4.872: 1.000: 1 5151251_time1 (Format): time2 (CONNECT): time3 (operator) = 4.725: 1.147: 1 5311091_time1 (Format): time2 (CONNECT): time3 (operator) = 4.872: 1.000: 1 5311251_time1 (Format): time2 (CONNECT): time3 (operator) = 4.872: 1.147: 1 5311091_time1 (Format): time2 (CONNECT): time3 (operator) = 4.872: 1.000: 1 5311091_time1 (Format): time2 (CONNECT): time3 (operator) = 4.872: 1.000: 1 5311091_time1 (Format): time2 (CONNECT): time3 (operator) = 4.872: 1.000: 1 5311251_time1 (Format): time2 (CONNECT): time3 (operator) = 4.872: 1.147: 1 531109125time1 (Format): time2 (CONNECT): time3 (operator) = 4.248: 0.872: 1
Cause:
String. format and string. connect performs the New Address Allocation and inbound stack operations, but string. the format checks and judges each character in the stack. When a replacement character such as {\ D +} appears, the character sequence corresponding to {\ D +} is imported into the stack. connect only performs inbound check and judgment on the characters of the inbound stack. When the stack entry operation is complete, stack operations are performed to put the characters in the stack into the stack in sequence. Theoretically, the longer the string. Format operation, the lower the efficiency.Note: \ D + indicates a number, such as string format = "My {0} is {1}"; 0 and 1