Compositite Proxy_SoA_AoS
情景1:
一个游戏 有100个对象的X坐标需要全部移动;
class Creature
{
public byte Age;
public int X, Y;
}
class Program
{
static void Main(string[] args)
{
Creature[] creatures = new Creature[100];
foreach (var item in creatures)
{
item.X++;
}
}
}
而Cpu在内存中的实际查找情况是 1. Age X++ Y =>2. Age X++ Y =>3. Age X++ Y =>4. Age X++ Y....
我们转换一种方式进行存储:[Age,Age,Age,Age...] [X,X,X,X..] [Y,Y,Y,Y..]会对计算效率进行一定的提升
class Creature
{
public byte Age;
public int X, Y;
}
class Creatures
{
private int size;
private byte[] age;
private int[] x, y;
public Creatures(int size)
{
this.size = size;
age = new byte[size];
x = new int[size];
y = new int[size];
}
public struct CreatureProxy
{
private readonly Creatures creatures;
private readonly int index;
public CreatureProxy(Creatures creatures,int index)
{
this.creatures = creatures;
this.index = index;
}
public ref byte Age => ref creatures.age[index];
public ref int X => ref creatures.x[index];
public ref int Y => ref creatures.y[index];
}
public IEnumerator<CreatureProxy> GetEnumerator()
{
for (int i = 0; i < size; i++)
{
yield return new CreatureProxy(this, i);
}
}
}
class Program
{
static void Main(string[] args)
{
Creature[] creatures = new Creature[100];
foreach (var item in creatures)
{
item.X++;
}
var creaturePoxy = new Creatures(100);
foreach (var item in creaturePoxy)
{
item.X++;
}
}
}