30.06.2013 Views

Under the Hood of .NET Memory Management - Simple Talk

Under the Hood of .NET Memory Management - Simple Talk

Under the Hood of .NET Memory Management - Simple Talk

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4: Common <strong>Memory</strong> Problems<br />

Once <strong>the</strong> compiler works its magic, we get <strong>the</strong> code in Listing 4.48.<br />

[CompilerGenerated]<br />

private sealed class c__DisplayClass4<br />

{<br />

// Fields<br />

public Person targetEmployee;<br />

// Methods<br />

public bool b__3(Employee d)<br />

{<br />

return (d.ReportsTo == this.targetEmployee);<br />

}<br />

}<br />

Listing 4.48: The dynamic class generated enclosing <strong>the</strong> captured variables.<br />

The anonymous method is actually "enclosed" in a dynamic compiler-generated class,<br />

which includes a member variable for every external variable that <strong>the</strong> anonymous method<br />

references. This generated class and all enclosed variables will stay alive as long as <strong>the</strong><br />

delegate is accessible. This extended lifetime can dramatically delay when variables are<br />

eligible for garbage collection, and thus create situations that look like a memory leak.<br />

Avoid closures with memory intensive variables.<br />

Effects <strong>of</strong> Yield<br />

In C#, <strong>the</strong> yield keyword is used to generate an implementation <strong>of</strong> <strong>the</strong> Iterator<br />

pattern, which in .<strong>NET</strong> is an implementation <strong>of</strong> IEnumerator. It is a useful and underutilized<br />

feature <strong>of</strong> <strong>the</strong> C# language that can greatly reduce <strong>the</strong> complexity <strong>of</strong> iterating<br />

lazy or dynamic collections <strong>of</strong> objects. Methods using <strong>the</strong> yield keyword must return<br />

IEnumerable, IEnumerable, IEnumerator, or IEnumerator. For type-safety<br />

and semantics, it is <strong>of</strong>ten preferred to return IEnumerable.<br />

129

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!