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

本文介绍了一个使用 C# 实现的自定义整数解析器,并通过与内置 int.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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值