Monday, August 20, 2007

Efficient use of Iterators and Delegates

This is a good read. It shows how to effectually use iterators to make garbage collection efficient and to lower memory usage. It also shows how to use delegates to also improve on this concept.

http://msdn2.microsoft.com/en-us/vcsharp/bb264519.aspx

Take the initial uneffecient example:

// First attempt:
public List PeopleIKnowInNewYork()
{
IEnumerable newYorkNumbers = PhoneBook.FindListFor(“New York”);
List peopleIKnow = new List();

foreach ( PhoneBookEntry ph in newYorkNumbers)
{
string name = string.Format(“{0} {1}”, ph.FirstName,
ph.LastName);

if ( RecognizePerson( name ) )
peopleIKnow.Add(name);
}

return peopleIKnow;
}

// Fifth attempt:public

IEnumerable PeopleIKnowInNewYork()
{
IEnumerable newYorkNumbers =
PhoneBook.FindListFor(“New York”);
IEnumerable names = Transform(newYorkNumbers,
delegate(PhoneEntry entry)
{
return string.Format(“{0} {1}”, entry.FirstName, entry.LastName);
});
return Filter(names,
delegate(string name)
{
return RecognizePerson(name);
}
);
}

No comments:

Post a Comment