- Home /
Does the use of new VectorX within a loop cause a memory leak?
So previously I had an issue in C++ where using 'new Something' within a loop or function that is repeatedly called would cause a memory leak (as I never deleted/destroyed it after it was finished). I was wondering if the same thing happens in Unity with vectors.
As it is easier for me to define a new vector all at once using;
Vector3 myVector = new Vector3 (X, Y, Z);
In my code I have this within a for loop (as well as several other constantly called functions including update) and was wanting to check whether it will cause a memory leak, or if Unity automatically deletes the 'new vector3...' once its done (since it wasn't an actual variable).
Also, within things like Visual Studio, I can easily tell iftheres a memory leak as when debugging the VS creates a new process for running the debugger, so I can easily see in task manager whether or not I have a memory leak. But in Unity I'm uncertain if this is also the case (IE if a leak happens, the memory usage for 'Unity3d.exe' will constantly increase) or if it will remain constant, or if there is another way to determine if there is a memory leak (even a tiny one)
I apologize if this was asked before, but no suggestions came up answering my question(s).
Answer by karljj1 · Feb 01, 2015 at 11:22 PM
.Net is a managed language, it looks after the memory. Objects are automatically freed when they are no longer needed by the application where in C++ you must free the object yourself using delete. So no you should not get a memory leak HOWEVER in Unity some objects are not managed and must be destroyed manually or by forcing Unity to do it for you. Fortunately Vector is not one of them :)
On top of that, Vector is a structure so they are added to the stack and "destroyed" when out of scope. Actually, they are not really destroyed, the stack pointer is just moving down and the old data will be overwritten. So your loop is not doing much to the Heap memory go ahead and use it.