Is there a way to tell the .NET to allocate a new object in generation 2 heap. I have a problem where I need to allocate approximately 200 MB of objects, do something with them, and throw them away. What happens here is that all the data gets copied two times (from gen0 to gen1 and then from gen1 to gen2).
Framework works differently with big objects that with the normal objects. So briefly it put big objects in generation and don't move it when reallocate heap.
There is no way to allocate directly in generation 2. All allocations happen in generation 0 and for large objects on the LOH.
However, data is generally not copied when objects move to a new generation. Instead the start points of the different heaps are moved. The objects may be moved due to compaction of the heap, but that is a different story.
If it is important to store objects in generation 2, you could reuse the instances. I.e. make some init method on the types and call this instead of creating new instances.
If you want to fix your objects so the framework cannot move them, you can try using GCHandle
to pin the objects. This is usually used for P/Invoke but will give the result you're looking for. I have my doubts that you're seeing slowdowns due to generational compaction but I can't say without seeing your profiling data.
http://msdn.microsoft.com/en-us/library/khk3k17t%28v=VS.71%29.aspx
Example:
var q = new MyObject();
var handle = GCHandle.Alloc(q, GCHandleType.Pinned);
// use object
handle.Free();