一个自定义空间结构的三种数据格式的运行效率比较
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
SpaceUnit[] space_3x3x3 = new SpaceUnit[27];
int n = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
space_3x3x3[n]._X = i;
space_3x3x3[n]._Y = j;
space_3x3x3[n]._Z = k;
space_3x3x3[n]._TYPE = 0;
space_3x3x3[n]._OCCUPYSTATE = false;
n++;
}
}
}
stopwatch.Stop();
Debug.LogError(stopwatch.Elapsed.TotalMilliseconds);
stopwatch.Reset();
stopwatch.Start();
float[,,,] _space_3x3x3 = new float[3, 3, 3, 2];
for (int i = 0; i < 3; i++)
{
for (int j= 0; j < 3; j++)
{
for (int k = 0; k < 3; k++)
{
_space_3x3x3[i, j, k, 0] = 0;
_space_3x3x3[i, j, k, 1] = 0;
}
}
}
stopwatch.Stop();
Debug.LogError(stopwatch.Elapsed.TotalMilliseconds);
stopwatch.Reset();
stopwatch.Start();
float[][][][] _sp = new float[3][][][];
for (int i = 0; i < _sp.Length; i++)
{
_sp[i] = new float[3][][];
for (int j = 0; j < _sp[i].Length; j++)
{
_sp[i][j] = new float[3][];
for (int k = 0; k < _sp[i][j].Length; k++)
{
_sp[i][j][k] = new float[2];
_sp[i][j][k][0] = 0;
_sp[i][j][k][1] = 0;
}
}
}
stopwatch.Stop();
Debug.LogError(stopwatch.Elapsed.TotalMilliseconds);
stopwatch.Reset();
public struct SpaceUnit
{
/// <summary>
/// 当前空间区域x坐标
/// </summary>
public int _X;
/// <summary>
/// 当前空间区域y坐标
/// </summary>
public int _Y;
/// <summary>
/// 当前空间区域z坐标
/// </summary>
public int _Z;
/// <summary>
/// 当前空间区域的占用状态
/// </summary>
public bool _OCCUPYSTATE;
/// <summary>
/// 当前空间区域的占用类型
/// </summary>
public int _TYPE;
}
后续
之后了解到了Cache友好代码,按照其理解应该是多维数组的速度更快,因为在实际操作中多维数组的的底层是一个连续的一维数组,即在内存中是连续存在的,而交错数组不是,经过指针输出地址可以很明显的看出来。不过所幸经过搜索资料找到了最终原因,因为交错数组内部有特殊的IL指令会导致JIT编译器生成优化的代码所以会导致交错数组在执行时会比多维数组快,尽管其在内存中可能并不是连续存在的。
在实际测试中还遇到一种情况是,在获取数组各个元素的内存地址时交错数组获取时间明显要比多维数组时间要长,可能是因为交错数组内存不连续导致的。