BitCovert,与移位,加法性能比较

 

 

今天刚测试了一下BitCovert,与移位,加法性能比较,

采用的代码如下:

代码
1 private static long IpToInt(string ip)
2 {
3 char[] separator = new char[] { '.' };
4 if (ip.Split(separator).Length == 3)
5 {
6 ip = ip + ".0";
7 }
8 string[] strArray = ip.Split(separator);
9 long num2 = ((long.Parse(strArray[0]) * 0x100L) * 0x100L) * 0x100L;
10 long num3 = (long.Parse(strArray[1]) * 0x100L) * 0x100L;
11 long num4 = long.Parse(strArray[2]) * 0x100L;
12 long num5 = long.Parse(strArray[3]);
13 return (((num2 + num3) + num4) + num5);
14 }
15
16 private static long IpToInt2(string ip)
17 {
18 string[] ipbytes = ip.Split('.');
19
20 byte[] dat = new byte[4];
21
22 int l=ipbytes.Length;
23
24 for (int i=0;i<l;i++)
25 {
26 dat[3-i] = (byte)int.Parse(ipbytes[i]);
27 }
28
29 return BitConverter.ToUInt32(dat,0);
30 }
31
32
33 private static long IpToIntBitMove(string ip)
34 {
35 string[] ipbytes = ip.Split('.');
36 long[] numbers = new long[4];
37 int l=ipbytes.Length;
38 for (int i = 0; i < l; i++)
39 {
40 numbers[i] = long.Parse(ipbytes[i]);
41 }
42 return numbers[3] + (numbers[2] << 8) + (numbers[1] << 16) + (numbers[0] << 24);
43 }

测试结果发现:使用BitConvert方式速度最快,明显优于第一种方式的乘法运算;

而移位算法则和BitConvert方法速度相当,在100000次以上的测试中BitConvert大概比移位方式少几十毫秒。

所以开发中优先考虑使用BitConvert(符合该实例特征有效)

这只是在byte[]数组转整型过程中得到体现,至于实际运算肯定是移位运算是最快。

 

 

 

posted @ 2010-06-01 13:09  dobit  阅读(630)  评论(0编辑  收藏  举报