Temporary Objects Are Free

1/29/2004 2:19:32 PM

Temporary Objects Are Free

This is a followup to my previous post, Are Objects Cheap? Here is an article that talks about garbage collection and performance. It actually deals with Java, but, from reading the article, it appears that .NET and Java both use virtually identical garbage collection schemes.

After reading the article, I made the startling discovery that using a lot of temporary objects actually will have almost no impact on performance, assuming the stack isn't too deep.

The garbage collector never visits dead objects and copies all the live objects to the next generation. If since the last collection, no references were changed from older objects, then the next Gen 0 garbage collection will only visit references on the stack, which is usually not very deep, and any live objects in the Gen 0 heap. (The runtime recognizes that gen 1 and gen 2 need not be visited, because there could not possibly be a reference from those heaps to a gen 0 object, if none of the references in those heap have changed to point to a Gen 0 since the last collection; a further optimization handles cases where a few references have changed.)

The incremental cost of allocating lots of temporary objects is really then just the cost of performing a stack walk per Gen 0 collection (plus the cost of copying the few temporary objects whose lifetimes where interrupted by the garbage collector). The stack is usually not deep, so the walk is cheap. Any non-temporary object would have been copied to Gen 1 only once, regardless of the frequency of the garbage collection.

NOTE: A proper analysis would require actual performance tests.






Net Undocumented is a blog about the internals of .NET including Xamarin implementations. Other topics include managed and web languages (C#, C++, Javascript), computer science theory, software engineering and software entrepreneurship.

Social Media