比如下面的代码:
short[] sts={0,1,100,200};
for(int i=0;i<sts.Lenght;i++)
{
if(sts[i]>50)
{
.....
}
}由于以上访问数组的方式速度不太理想,所以想改成指针方式访问数组,请问该如何编写?
short[] sts={0,1,100,200};
for(int i=0;i<sts.Lenght;i++)
{
if(sts[i]>50)
{
.....
}
}由于以上访问数组的方式速度不太理想,所以想改成指针方式访问数组,请问该如何编写?
var p = (from a in _ary
select a).Single(a => a>50);
慢?!建一个全新的项目,里面什么都不做,仅是遍历一个 short[short.MaxValue] 的数组,需要多少时间?
如果把语句改成short st= sts[i]; if(st>50){....} 经过测试速度也是耽误在short st= sts[i]这句上。
以上的语句全是举例,实际访问short[]要大得多。
在你抗议数组访问速度慢之前,麻烦把你的其他代码统统踢出去,建立一个简单的测试环境。这个环境除了遍历数组之外什么都不做。然后才下结论。至少在我的环境中是飞快。。ps: 如果 short.MaxValue 都比你的数组小,我觉得你可以考虑是否真的一次过需要那么多数据, wince 并没有那么多资源可以挥霍。
我现在就是一个测试工程,因为要访问图片的每一个像素,图片比较大。如果单纯:int i=200;if(i==200){} 很快。(100ms) 但是如果if(short[i]==0){} 需要1400ms
// compile with: /unsafeclass TestCopy
{
// The unsafe keyword allows pointers to be used within the following method:
static unsafe void Copy(byte[] src, int srcIndex, byte[] dst, int dstIndex, int count)
{
if (src == null || srcIndex < 0 ||
dst == null || dstIndex < 0 || count < 0)
{
throw new System.ArgumentException();
} int srcLen = src.Length;
int dstLen = dst.Length;
if (srcLen - srcIndex < count || dstLen - dstIndex < count)
{
throw new System.ArgumentException();
} // The following fixed statement pins the location of the src and dst objects
// in memory so that they will not be moved by garbage collection.
fixed (byte* pSrc = src, pDst = dst)
{
byte* ps = pSrc;
byte* pd = pDst; // Loop over the count in blocks of 4 bytes, copying an integer (4 bytes) at a time:
for (int i = 0 ; i < count / 4 ; i++)
{
*((int*)pd) = *((int*)ps);
pd += 4;
ps += 4;
} // Complete the copy by moving any bytes that weren't moved in blocks of 4:
for (int i = 0; i < count % 4 ; i++)
{
*pd = *ps;
pd++;
ps++;
}
}
} static void Main()
{
byte[] a = new byte[100];
byte[] b = new byte[100]; for (int i = 0; i < 100; ++i)
{
a[i] = (byte)i;
} Copy(a, 0, b, 0, 100);
System.Console.WriteLine("The first 10 elements are:"); for (int i = 0; i < 10; ++i)
{
System.Console.Write(b[i] + " ");
}
System.Console.WriteLine("\n");
}
}
The first 10 elements are:
0 1 2 3 4 5 6 7 8 9