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 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 Slice->ToInt:{stopwatch。ElapsedMilliseconds}ms”); Console。ReadLine();}

擴充套件方法

ToInt原始碼是國內一位。Net大佬所寫。這裡只是改為擴充套件方法。

///

/// 在String型別加擴充套件方法/// /// /// 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;}/// /// 在ReadOnlySpan型別加擴充套件方法/// /// /// static int ToInt(this ReadOnlySpan 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;}

測試結果

Span效能測試對比

使用Span可以減少建立字串,減少記憶體分配,減少觸發GC