3.对这些数值求和。
internal class Program { static void Main(string[] args) { BenchmarkRunner.Run<LinqTest>(); Console.ReadKey(); } } [MemoryDiagnoser, MemoryRandomization] public class LinqTest { private static readonly string _row = "1,2,3,4,5,6,7,8,9,10"; [Benchmark] public void SumUsingLinq() { int sum = _row.Split(',').Select(int.Parse).Sum(); } [Benchmark(Baseline = true)] public void SumUsingForLoop() { var rowSpan = _row.AsSpan(); int sum = 0; for (int i = 0; i < rowSpan.Length; i++) { if (rowSpan[i] == ',') { sum += int.Parse(rowSpan.Slice(0, i)); rowSpan = rowSpan.Slice(i + 1); i = 0; } } } }Benchmark结果: