1

Is there a C# a list-like data structure that does not interact with Unity 3.5/4 .NET mono GC?

I know C# structs behave like scope variables in Unity and are not controlled via GC. I wonder if there is any free from GC if possible IEnumerable compatible List-like structure - with ability to filter, add elements into it and remove from it?

Robert Levy
  • 28,747
  • 6
  • 62
  • 94
DuckQueen
  • 772
  • 10
  • 62
  • 134
  • Main idea is to get a List alike item that would delete itself on going out from scope. – DuckQueen Mar 21 '13 at 15:37
  • Not sure if I follow: you mean you want to create a list object that is _not_ collected by the GC? EDIT: Or do you mean that items in the list would be automatically removed from that list once nothing else is referencing them? – Chris Sinclair Mar 21 '13 at 15:39
  • So you want something that will delete itself when it goes out of scope, but that isn't garbage collected when it's no longer useful? Isn't that exactly what the GC is for? – Bobson Mar 21 '13 at 15:43
  • @Bobson and ChrisSinclair I *think* the goal here is to reduce/eliminate GC managed allocations in order to prevent pauses caused by the collection. This is not uncommon in games, where a hiccup will occur due to too much memory pressure on the GC. – Reed Copsey Mar 21 '13 at 15:44
  • @ReedCopsey - That makes a lot of sense. – Bobson Mar 21 '13 at 15:46
  • You could write an list-like wrapper around a Memory Mapped File, I guess. – Matthew Watson Mar 21 '13 at 15:52
  • The it doesn't address the OP's question directly, but Unity has a [little writeup](http://docs.unity3d.com/Documentation/Manual/UnderstandingAutomaticMemoryManagement.html) on memory management. Nothing Unity specific, more a general GC overview. – Jerdak Mar 22 '13 at 12:21

2 Answers2

3

When using .NET, any object which is "growable" are going to be controlled by the GC, as it will need to have dynamic allocations.

If you the size is always small, you could potentially create a "collection" type wrapping a pointer from stackalloc to simulate this, but it's not going to behave like a normal list.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
2

One way of preventing a lot of allocations/deallocations and therefore causing the GC to run is to use a pool. This is where you allocate a certain number of objects, and then keep them allocated.

When you need a new object, you just take an unused one from the pool. You don't delete objects, you just mark them as unused.

See also this post: Should I use Pools for particles if i forced to re-init every particle every time i create them

Community
  • 1
  • 1
chue x
  • 18,573
  • 7
  • 56
  • 70