如果你可以使結構不變,你可以保存自己不必做大量的副本。 Eric Lippert有一些great posts about immutable structures。
編輯: 同樣,我不知道這是否會在你的情況下提高性能,但這裏是一個可能的設計,不可變對象的例子:
abstract class QuadTree<T>
{
public QuadTree(int width, int height)
{
this.Width = width;
this.Heigth = heigth;
}
public int Width { get; private set; }
public int Height { get; private set; }
public abstract T Get(int x, int y);
}
class MatrixQuadTree<T> : QuadTree<T>
{
private readonly T[,] matrix;
public QuadTree(T[,] matrix, int width, int heigth)
: base(width, heigth)
{
this.matrix = matrix;
}
public override T Get(int x, int y)
{
return this.matrix[x, y];
}
}
class CompositeQuadTree<T> : QuadTree<T>
{
private readonly QuadTree<T> topLeft;
private readonly QuadTree<T> topRight;
private readonly QuadTree<T> bottomLeft;
private readonly QuadTree<T> bottomRight;
public CompositeQuadTree(QuadTree<T> topLeft,
QuadTree<T> topRight, QuadTree<T> bottomLeft,
QuadTree<T> bottomRight)
: base(topLeft.Width + topRight.Width,
topLeft.Height + bottomLeft.Heigth)
{
// TODO: Do proper checks.
if (this.Width != topLeft.Width + bottomRight.Width)
throw Exception();
this.topLeft = topLeft;
this.topRight = topRight;
this.bottomLeft = bottomLeft;
this.bottomRight = bottomRight;
}
public override T Get(int x, int y)
{
if (x <= this.topLeft.Width)
{
if (y <= this.topLeft.Width)
{
return this.topLeft.Get(x, y);
}
else
{
return this.topLeft.Get(x, y + this.topLeft.Heigth);
}
}
else
{
if (y <= this.topLeft.Width)
{
return this.topRight.Get(x + this.topLeft.Width, y);
}
else
{
return this.topRight.Get(x + this.topLeft.Width,
y + this.topLeft.Heigth);
}
}
}
}
現在你就可以使用它如下:
T[,] _leaf1 = new T[64,64];
T[,] _leaf2 = new T[64,64];
T[,] _leaf3 = new T[64,64];
T[,] _leaf4 = new T[64,64];
// Populate leafs
QuadTree<T> l1 = new MatrixQuadTree<T>(_leaf1,64,64);
QuadTree<T> l2 = new MatrixQuadTree<T>(_leaf2,64,64);
QuadTree<T> l3 = new MatrixQuadTree<T>(_leaf3,64,64);
QuadTree<T> l4 = new MatrixQuadTree<T>(_leaf4,64,64);
// Instead of copying, you can no do this:
QuadTree<T> c = CompositeQuadTree<T>(l1,l2,l3,l4);
// And you can even make composites, of other composites:
QuadTree<T> c2 = CompositeQuadTree<T>(c,c,c,c);
// And you can read a value as follows:
T value = c2[30, 50];
同樣,我不知道這是否是您的情況適當的或所獲得的價值時,它是否給出了一個性能改進,因爲你有間接的級別。但是,有幾種方法可以改善這一點,但這取決於您真正需要做什麼。
祝你好運。
你怎麼reprent矩陣到底是什麼?總結如何?如果這些項目是引用類型,則只需複製一個指針(4/8字節),如果速度相當快。那裏只有4件(物品清單),對吧? – 2010-07-21 18:42:09
我加了一個例子。在我的結構中,'_leafX'會在子節點中,'void CopyInto(ref T [,],Point p)' – dlras2 2010-07-21 18:49:55
換句話說:您正在將矩陣的元素複製到其他矩陣?您可以使用'Array.CopyTo'或'Buffer.BlockCopy'(複製只需要幾個μs)。另外,如果你修改你的設計,使它不是'array [64]',而是'array [64 * 64]'並且使用模數('%')來檢查行,那麼它會更快。不知道你的性能瓶頸在哪裏。這取決於您訪問矩陣元素的頻率與您複製的頻率。 – 2010-07-22 06:21:10