【发布时间】:2012-11-29 22:24:16
【问题描述】:
字节优化能给您带来多大的性能提升(使它们成为 8、32、64 等的倍数)?
这是一个示例结构:
[StructLayout(LayoutKind.Explicit)]
public struct RenderItem
{
[FieldOffset(0)] byte[] mCoordinates = new byte[3]; //(x,y,z)
[FieldOffset(3)] short mUnitType;
}
所以我的问题是,做这样的事情有多重要:
[StructLayout(LayoutKind.Explicit)]
public struct RenderItem
{
[FieldOffset(0)] byte[] mCoordinates = new byte[3]; //(x,y,z)
[FieldOffset(4)] short mUnitType;
[FieldOffset(6)] byte[] mPadding = new byte[2]; //make total to 8 bytes
}
我确信它是“随大小缩放”的东西之一,所以我特别好奇会看到这个结构被使用大约 150,000 次来创建 VertexBuffer 对象的操作:
//int objType[,,] 3 dimensional int with object type information stored in it
int i = 0;
RenderItem vboItems[16 * 16 * 16 * 36] //x - 16, y - 16, z - 16, 36 verticies per object
For(int x = 0; x < 16; x++)
{
For(int y = 0; y < 16; y++)
{
For(int z = 0; z < 16; z++)
{
vboItems[i++] = (x,y,z,objType[x,y,z]);
}
}
}
//Put vboItems into a VBO
【问题讨论】:
-
查看alexonlinux.com/aligned-vs-unaligned-memory-access。另外,如果你不指定
FieldOffset,编译器会自动为你对齐结构。 -
它会自动对齐它们,但它会保证它们的顺序吗?我在几个地方看到它不能保证(因为它要进入 OpenGL,所以它的发送顺序很重要)
-
和哇,这是一个巨大的性能差异。
标签: c# opengl optimization structure