Question

I need to be able to iterate through all the objects of a specific type that are instantiated.

Traditionally I would cache these objects in a list and iterate through them when needed. However the objects are data heavy and there is a lot of them so Im concerned about keeping that many objects in memory throughout the duration of my program.

On the other hand Im looking into querying for them and storing the query in IEnumerable so that they are not actually stored in memory, but resolved on each iteration. However with this I'm concerned about the overhead of having to find each object on each iteration. ( I havnt yet decided on the mechanism that actually would do this yet efficiently, but thats another question )

It seems to me that this is one of those questions where you need to find a balence, caching may be memory intensive, but IEnumerable may be processing intensive. So Im wondering what others thoughts on this are.

Was it helpful?

Solution

Your initial approach with keeping them in a list is fine. You just need to ensure that you have removed the object from the list once you have finished working with it so that it becomes eligible for garbage collection. Otherwise you shouldn't be concerned with memory consumption with this approach if you are using reference types. The list will simply point to already existing objects in the memory (they won't be duplicated). You said that you wanted to retrieve all instances of some objects, so keeping a list of them is reasonable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top