C# merkkijono suorituskyky testi
13 August 2008Tässä on pieni suorituskyky testi C#:llä, joka vertailee merkkijonojenen merkkien käsittelyä eri toimintatavoilla.
Testin tulokset:
28218,75 ns per operation (RegEx)
765,63 ns per operation (StringBuilder)
687,50 ns per operation (char taulukot)
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Testi1 { class Program { static void Main(string[] args) { int loopCount = 1000000; long startTime, endTime; double nanoseconds; startTime = DateTime.Now.Ticks * 100; for (int x = 0; x < loopCount; x++) { ExtractNumbers1("Its is only 4 numbers but must be 1337"); } endTime = DateTime.Now.Ticks * 100; nanoseconds = ((double)(endTime - startTime)) / ((double)loopCount); Console.WriteLine(nanoseconds.ToString("F") + " ns per operation"); startTime = DateTime.Now.Ticks * 100; for (int x = 0; x < loopCount; x++) { ExtractNumbers2("Its is only 4 numbers but must be 1337"); } endTime = DateTime.Now.Ticks * 100; nanoseconds = ((double)(endTime - startTime)) / ((double)loopCount); Console.WriteLine(nanoseconds.ToString("F") + " ns per operation"); startTime = DateTime.Now.Ticks * 100; for (int x = 0; x < loopCount; x++) { ExtractNumbers3("Its is only 4 numbers but must be 1337"); } endTime = DateTime.Now.Ticks * 100; nanoseconds = ((double)(endTime - startTime)) / ((double)loopCount); Console.WriteLine(nanoseconds.ToString("F") + " ns per operation"); Console.Read(); } static string ExtractNumbers1(string expr) { return string.Join(null, System.Text.RegularExpressions.Regex.Split(expr, "[^\\d]")); } static string ExtractNumbers2(string expr) { StringBuilder sb = new StringBuilder(expr.Length); foreach (char ch in expr) { if (Char.IsDigit(ch)) sb.Append(ch); } return sb.ToString(); } static string ExtractNumbers3(string expr) { char[] nums = new char[expr.Length]; int pos = 0; foreach (char ch in expr) { if( Char.IsDigit( ch )) nums[pos++] = ch; } return new string ( nums, 0, pos ); } } }