前言
在<<。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
擴充套件方法
ToInt原始碼是國內一位。Net大佬所寫。這裡只是改為擴充套件方法。
///
測試結果
使用Span可以減少建立字串,減少記憶體分配,減少觸發GC