【发布时间】:2015-10-04 18:02:06
【问题描述】:
因为我的目标是超越 List<T>
我正在测试数组,发现很少有开始测试的起点
在尝试从屏幕上捕获位图之前,我已经对此进行了测试,
并且测试证明使用就足够了。
我的问题是除了 byte[]
说我想要一个数据存储单元来利用非托管/不安全的优势
public unsafe struct NusT
{
public unsafe int vi;
public unsafe bool vb;
}
而不是填充列表
我按如下方式初始化结构:1)
NusT n;
n.vi= 90;
n.vb=true
我在测试以下内容后对此进行了测试:2)
NusT n = new NusT(){vi=90, vb=true};
这个测试是在测试之后进行的 :3)
NusT n = new NusT("90", true);
我认为最后两个结果相同,但第一个结果非常快,因为我没有创建对象所以
NusT n-> instructions- 1
n.vi=90 -> instructions- 1
n.vb=true -> instructions- 1
现在我尽量减少了我可以做的事情,这从一门课开始: whitch 甚至比上面的 2 和 3 还要糟糕,因为它也使用属性
class bigAndSlow
{
public int a { get; private set;}
public bool b { get; private set;}
public string c { get; private set;}
public bigAndSlow(int .. ,boo .. , string.. )
{
initialise ...
}
}
所以现在是最终决定的时候
public unsafe struct NusT
{
public unsafe int vi;
public unsafe bool vb;
}
我怎样才能实现这个极快的数据单元来使用 Copy() on
NusT[] NustyArr;
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 ArgumentException();
}
int srcLen = src.Length;
int dstLen = dst.Length;
if (srcLen - srcIndex < count ||
dstLen - dstIndex < count)
{
throw new 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 n = 0; n < count / 4; n++)
{
*((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 n = 0; n < count % 4; n++)
{
*pd = *ps;
pd++;
ps++;
}
}
}
static void Main(string[] args)
{
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);
Console.WriteLine("The first 10 elements are:");
for (int i = 0; i < 10; ++i)
Console.Write(b[i] + " ");
Console.WriteLine("\n");
}
【问题讨论】:
-
只是一个旁注。当结构标记为不安全时,您不必将字段标记为不安全。
-
@M.kazemAkhgary 谢谢我不确定,我什至想把 * nex 放到 int 和 bool int*...
-
我不明白你想要达到什么目的。你想复制“NusT”的数组吗?使用 memcpy。
标签: c# performance unit-testing data-structures unsafe