快速的Int32.Parse,比系统的快。

using System; namespace CSharpConsole01 { public static class ExternClass { public static int MyParse(this string text) { text = text.PadLeft(10, '0'); if (text[0] < '0' || text[0] > '9' || text[1] < '0' || text[1] > '9' || text[2] < '0' || text[2] > '9' || text[3] < '0' || text[3] > '9' || text[4] < '0' || text[4] > '9' || text[5] < '0' || text[5] > '9' || text[6] < '0' || text[6] > '9' || text[7] < '0' || text[7] > '9' || text[8] < '0' || text[8] > '9' || text[9] < '0' || text[9] > '9') { throw new FormatException(); } return (text[0] - '0') * 1000000000 + (text[1] - '0') * 100000000 + (text[2] - '0') * 10000000 + (text[3] - '0') * 1000000 + (text[4] - '0') * 100000 + (text[5] - '0') * 10000 + (text[6] - '0') * 1000 + (text[7] - '0') * 100 + (text[8] - '0') * 10 + (text[9] - '0'); } } class Program { [STAThreadAttribute] static void Main(string[] args) { Random rnd = new Random(Environment.TickCount); string[] list = new string[10000];//生成10000个测试数据 int[] myparse = new int[10000]; int[] sysparse = new int[10000]; for (int i = 0; i < 10000; i++) list[i] = rnd.Next(0, int.MaxValue).ToString(); //MyParse int tick1 = Environment.TickCount; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 10000; j++) { myparse[j] = list[j].MyParse(); } } tick1 = Environment.TickCount - tick1; int tick2 = Environment.TickCount; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 10000; j++) { sysparse[j] = int.Parse(list[j]); //int.TryParse(list[j], out sysparse[j]); } } tick2 = Environment.TickCount - tick2; Console.WriteLine("MyParse:" + tick1.ToString()); Console.WriteLine("int.Parse:" + tick2.ToString()); Console.ReadKey(); } } }

运行结果

MyParse:3986
int.Parse:5157

你可能感兴趣的:(快速的Int32.Parse,比系统的快。)