考慮到sql server以及c#,最多只能用decimal類型,也就是29位的數字,做了下面這個數字型id生 成器:
class Program { static void Main(string[] args) { int i = 100000; Timing t = new Timing(); t.Start(); while(i-->0) UniqueIdGenerator.Next(); t.Stop(); t.Display(""); } } public static class UniqueIdGeneratorHelper { public static long IP2Long(String strIP) { long[] ip = new long[4]; string[] s = strIP.Split('.'); ip[0] = long.Parse(s[0]); ip[1] = long.Parse(s[1]); ip[2] = long.Parse(s[2]); ip[3] = long.Parse(s[3]); return (ip[0] << 24) + (ip[1] << 16) + (ip[2] << 8) + ip[3]; } } public static class UniqueIdGenerator { static UniqueIdGenerator() { ip = UniqueIdGeneratorHelper.IP2Long("192.168.1.21");//需要自己從配置文件中讀取 } private static long ip=0; public static decimal Next() { return decimal.Parse(DateTime.Now.ToString("yyyyMMddHHmmssff") + ip.ToString() + GetSequence().ToString()); } private static int curSeq = 1; private static object o = 1; private static int GetSequence() { lock (o) { if (curSeq > 999) curSeq = 1; return curSeq++; } } }
十萬次請求,花了半秒不到,應該還行。
查看本欄目