Span性能测试对比
前言
在上一篇 在.Net Core中使用Span ,认识并了解Span使用,及使用Span可以减少GC回收.这里还是简单的做一个测试(纯属娱乐).主要是测试字符串截取并转int.因为这里以性能为主,通过扩展ToInt方法替代IntParse方法.
测试代码
static void Main(string[] args)
{
string str = "hello csharp,20181109";
int times = 100000; //循环执行次数
Stopwatch stopwatch = new Stopwatch();
int val1 = str.Substring(13, 8).ToInt(); //预热
Console.WriteLine($"String Substring Convert val={val1}");
stopwatch.Restart();
for (int i = 0; i < times; i++)
{
int temp = str.Substring(13, 8).ToInt();
}
stopwatch.Stop();
Console.WriteLine($"String Substring->ToInt:{stopwatch.ElapsedMilliseconds}ms");
int val2 = str.AsSpan().Slice(13, 8).ToInt(); //预热
Console.WriteLine($"ReadOnlySpan<char> Slice Convert val={val2}");
stopwatch.Restart();
for (int i = 0; i < times; i++)
{
int temp = str.AsSpan().Slice(13, 8).ToInt();
}
stopwatch.Stop();
Console.WriteLine($"ReadOnlySpan<char> Slice->ToInt:{stopwatch.ElapsedMilliseconds}ms");
Console.ReadLine();
}
扩展方法
/// <summary>
/// 在String类型加扩展方法
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static int ToInt(this string s)
{
var m = s[0] == '-' ? -1 : 1;
var endi = m == 1 ? 0 : 1;
int v = 0, tmp = 0, i = s.Length;
while (i > endi)
{
tmp = s[--i] - 48;
if (tmp < 0 || tmp > 9) throw new FormatException("It's not a number.");
checked { v += tmp * m; }
m *= 10;
}
return v;
}
/// <summary>
/// 在ReadOnlySpan类型加扩展方法
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
static int ToInt(this ReadOnlySpan<char> s)
{
var m = s[0] == '-' ? -1 : 1;
var endi = m == 1 ? 0 : 1;
int v = 0, tmp = 0, i = s.Length;
while (i > endi)
{
tmp = s[--i] - 48;
if (tmp < 0 || tmp > 9) throw new FormatException("It's not a number.");
checked { v += tmp * m; }
m *= 10;
}
return v;
}
效果
秋风
2018-11-09