我有以下基于代码的on this question. 在这里拉小提琴.https://dotnetfiddle.net/vchYHj
using System;
using System.Diagnostics;
public class Program
{
public static void Main()
{
ReadOnlySpan<byte> r = stackalloc byte[] { 52, 48, 48, 55, 48 };
var sw = new Stopwatch();
int result = 0;
sw.Restart();
for (int i=0; i<10000000; i++) result = Test1(r);
sw.Stop();
Console.WriteLine($"Test1 took {sw.ElapsedMilliseconds}ms {result}");
sw.Restart();
for (int i=0; i<10000000; i++) result = Test2(r);
sw.Stop();
Console.WriteLine($"Test2 took {sw.ElapsedMilliseconds}ms {result}");
}
public static int Test1(ReadOnlySpan<byte> source)
{
int answer = 0;
int index = 0;
int c = source[index];
answer = c - '0';
while (true)
{
index++;
if ((uint)index >= (uint)source.Length)
break;
c = source[index];
answer = answer * 10 + c - '0';
}
return answer;
}
public static int Test2(ReadOnlySpan<byte> data)
{
if (System.Buffers.Text.Utf8Parser.TryParse(data, out int value, out int bytes))
{
return(value);
}
else
return(0);
}
}
Test1 took 244ms 40070
Test2 took 99ms 40070
为什么第二种方法Test1
在.NET小提琴上要慢得多,因为它完全是从.NET开源复制而来的,而且更简单?