C#中的字符串内插$对⽐string.Format C# 10.0 对字符串插值做了点提升,⽀持开发⼈员对字符串进⾏花式内插。
附官⽅教程:
先说下我机器的配置:
1#region 测试代码
2var a = 3;
3var b = 2;
4var list = new List<int>();
5Console.WriteLine("strat method one");
6for (int j = 0; j < 10; j++)
7{
8    var dt1 = DateTime.Now;
9    //Console.WriteLine(dt1.ToString("HH:mm ffff"));
10    for (int i = 0; i < 1_0000_0000; i++)
11    {
12        var c = $"{a} + {b} = {a + b}";
13    }
14    var dt2 = DateTime.Now;
15    //Console.WriteLine(dt2.ToString("HH:mm ffff"));
16    Console.WriteLine("times " + j + " : " + (dt2 - dt1).Milliseconds);
17    list.Add((dt2 - dt1).Milliseconds);
18}
19list.Remove(list.Max());
20list.Remove(list.Min());
21Console.WriteLine(list.Average());
22
23list.Clear();
24Console.WriteLine("strat method two");
25for (int j = 0; j < 10; j++)
26{
27    var dt1 = DateTime.Now;
28    //Console.WriteLine(dt1.ToString("HH:mm ffff"));
29    for (int i = 0; i < 1_0000_0000; i++)
30    {
31        var c = string.Format("{0} + {1} = {2}", a, b, a + b);
32    }
33    var dt2 = DateTime.Now;
34    //Console.WriteLine(dt2.ToString("HH:mm ffff"));
35    Console.WriteLine("times " + j + " : " + (dt2 - dt1).Milliseconds);
36    list.Add((dt2 - dt1).Milliseconds);
37}
38list.Remove(list.Max());
39list.Remove(list.Min());
40Console.WriteLine(list.Average());
41#endregion
输出结果:
结论:从测试结果来说,string.Format占⽤的cpu资源更稳定,$语法糖就有些飘忽不定。但是⽆论是从功能扩展还是长期性能考虑来看的话,只能说微软⽜逼,语法糖真⾹。
附录:之前的测试代码反编译⼀下的结果
writeline教程
1int a = 3;
2int b = 2;
3List<int> list = new List<int>();
4Console.WriteLine("strat method one");
5for (int i = 0; i < 10; i++)
6{
7 DateTime dt = DateTime.Now;
8 for (int j = 0; j < 100000000; j++)
9 {
10  DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(6, 3);
11  defaultInterpolatedStringHandler.AppendFormatted<int>(a);
12  defaultInterpolatedStringHandler.AppendLiteral(" + ");
13  defaultInterpolatedStringHandler.AppendFormatted<int>(b);
14  defaultInterpolatedStringHandler.AppendLiteral(" = ");
15  defaultInterpolatedStringHandler.AppendFormatted<int>(a + b);
16  string c = defaultInterpolatedStringHandler.ToStringAndClear();
17 }
18 DateTime dt2 = DateTime.Now;
19 Console.WriteLine("times " + i.ToString() + " : " + (dt2 - dt).Milliseconds.ToString());
20 list.Add((dt2 - dt).Milliseconds);
21}
22list.Remove(list.Max());
23list.Remove(list.Min());
24Console.WriteLine(list.Average());
25list.Clear();
26Console.WriteLine("strat method two");
27for (int k = 0; k < 10; k++)
28{
29 DateTime dt3 = DateTime.Now;
30 for (int l = 0; l < 100000000; l++)
31 {
32  string c2 = string.Format("{0} + {1} = {2}", a, b, a + b);
33 }
34 DateTime dt4 = DateTime.Now;
35 Console.WriteLine("times " + k.ToString() + " : " + (dt4 - dt3).Milliseconds.ToString());
36 list.Add((dt4 - dt3).Milliseconds);
37}
38list.Remove(list.Max());
39list.Remove(list.Min());
40Console.WriteLine(list.Average());

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。