mathnet / mathnet-numerics

Math.NET Numerics
http://numerics.mathdotnet.com
MIT License
3.48k stars 895 forks source link

DenseMatrix.OfRowArrays().LU() Memory Leak #1050

Open tianmafly opened 10 months ago

tianmafly commented 10 months ago

hi, I test the code, and find the memory of pc is continuously growing。 Does I use not correct? thanks.

float[][] a= ...; DenseMatrix matrix= DenseMatrix.OfRowArrays(a);

float[][] b= ...; for (int i = 0; i < b.Length; i++) { DenseVector v = new DenseVector(b[i]); // Memory Leak LU l = matrix.LU(); Vector datas = l.Solve(v); }

wo80 commented 9 months ago

It seems you are factorizing the same matrix in each loop. This will allocate new memory in each iteration creating memory pressure. It's not a memory leak, the memory will be garbage collected. Still it might impact the runtime.

Creating the LU factorization before the loop should solve your problem.

There's also an overload of the Solve method to avoid allocating memory for the result inside the loop. Just allocate your datas vector before the loop and then use

https://github.com/mathnet/mathnet-numerics/blob/e010de79d70f197112cdc86d2e637f5db2968d24/src/Numerics/LinearAlgebra/Single/Factorization/DenseLU.cs#L128-L133