如果我有结构数组MyStruct[]
:
struct MyStruct
{
float x;
float y;
}
而且它比我执行 float[] -> x = > i; 慢。 y => i + 1(因此该数组比结构体数组大 2 倍)。
10,000 个项目相互比较的时间差(内部有两个 for):结构体 500 毫秒,仅包含 float 的数组 - 78 毫秒
我想,该结构看起来像例如。 float、int 等(在堆上)。
最佳答案
首先,结构不一定出现在堆上 - 它们可以而且经常出现在堆栈上。
关于您的性能测量,我认为您的测试一定是错误的。使用此基准测试代码,我获得了两种类型几乎相同的性能结果:
TwoFloats[] a = new TwoFloats[10000];
float[] b = new float[20000];
void test1()
{
int count = 0;
for (int i = 0; i < 10000; i += 1)
{
if (a[i].x < 10) count++;
}
}
void test2()
{
int count = 0;
for (int i = 0; i < 20000; i += 2)
{
if (b[i] < 10) count++;
}
}
结果:
Method Iterations per second test1 55200000 test2 54800000
关于c# - 为什么struct比float慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3867331/