- Home /
foreach on generics containers will allocate on the heap?
Hi, guys,
I just find out in Unity's profiler that calling foreach on a generic container will create garbage on heap( around 24B ).
And there's no garbage if I use the GetEnumerator and MoveNext() to run loop on the container.
That's kind of weird, because it doesn't seem to create garbage in a program compiled with Microsoft's .Net ( I didn't see such memory allocation with VisualStudio's profiler )
List<int> m_lst = new List<int>();
void Update()
{
foreach(var i in m_lst ){} //allocate 24B every frame
}
Is it always like this? or just because I upgraded to Unity4.3? Could someone give a definite answer or take a test on older version of unity?
I suggest reading this Gamasutra article about memory management in Unity. Especially part entitled "Should you avoid foreach loops".
wow, very nice article, thanks ArkaneX. I think this one is worth reading for every unity programmer. Unity should in their documents make an obvious link to this one :)
Your answer
Follow this Question
Related Questions
How to set a value for each level without using a switch statement 2 Answers
Is there a way to organize tracking of collisions? 0 Answers
[C#] Calling Interface from Array of MonoBehaviour 2 Answers
Foreach - what am I doing wrong? 1 Answer
Getting all objects with a tag and inserting them into an array of gameobject 1 Answer