I had a slow memory leak in an app, that I tracked down to Vector3D methods that were instantiating and returning new Vector3D objects (code below). I thought this was legal, as the new object exists on the function stack and will not be referenced once a calculation is complete. The profiler showed that these methods were producing stray Vector3D objects that weren’t being garbage collected:
public Vector3D vectorProduct(Vector3D a, Vector3D b)
{
return new Vector3D(a.y*b.z-b.y*a.z, a.z*b.x-b.z*a.x, a.x*b.y-b.x*a.y);
}
public Vector3D getNormal(Vector3D a, Vector3D b)
{
return vectorProduct(a,b).normalize();
}
The vectorProduct() method returns a new Vector3D, so the math operations can be chained as in getNormal().
I fixed this easily enough by instantiating Vector3D objects to hold answers and then reusing them instead of creating new ones for each calculation. Still I was surprised that this approach leaked memory. Is this bad form, or am I missing something else?