SlimDX VertexDeclaration memory leak? - How to avoid it?
I've got a problem with my SlimDX / DirectX application. I've got a loop made using SlimDX's MessagePump
, and I had a problem with my application using excessive amount of memory, which was increasing. I was trying to find what part of my code does it, and I've found out that it's probably this:
var vertexElems = new[] {
new VertexElement(0, 0, DeclarationType.Float4, DeclarationMethod.Default, DeclarationUsage.PositionTransformed, 0),
new VertexElement(0, 16, DeclarationType.Color, DeclarationMethod.Default, DeclarationUsage.Color, 0),
VertexElement.VertexDeclarationEnd
};
var vertexDecl = new VertexDeclaration(device, vertexElems);
This part of code is running in a constant loop (MessagePump.Run()
), and each second it eats around 2 MB more of memory.
How to avoid the memo开发者_开发技巧ry leak in VertexDeclaration
? Maybe there's something wrong in the C++ source code of SlimDX's VertexDeclaration? Or do I have to define the VertexDeclaration
outside of the loop? And why doesn't the garbage collector take care of it?
And a similar question related to this: Is it a problem if I define new variables in a loop, when I actually only use them once? For example this code:
Matrix T, S;
T = Matrix.Translation(mShipPos.X, mShipPos.Y, mShipPos.Z);
S = Matrix.Scaling(20.0f, 20.0f, 0.0f);
mSprite.Transform = S * T;
runs in a loop. Is it a problem and should I define matrixes T and S outside of the loop, or does the garbage collector take care of this? I've been looking into several example source codes and many programmers do this - but doesn't it use more and more memory when running in a loop?
For any variables/references that you will be using repeatedly, without them changing, it is a good idea to declare them somewhere outside of the loop.
Also many types in SlimDX implement the IDisposable
interface, so it is a good idea to call .Dispose()
on them when you're done to clean them up.
SlimDX is in the world of unmanaged code interop (and even more so, since it runs a graphics API which also allocates and frees memory on the graphics card), which has a whole new host of problems that you're not going to find in purely managed code. This is why you most likely do not find the garbage collector acting as you would expect it to.
精彩评论