This morning I put the finishing touches to Flyweights, a proof-of-concept .NET memory management library hosted at Google Code. The purpose of the library is simple; if your application stores a number of equal objects that never change, why not just store one object and share a reference to it?

Flyweight<string> a = "Richard";
Flyweight<string> b = "Richard";
Flyweight<string> c = "Richard";
Flyweight<string> d = "Richard";
Flyweight<string> e = "Richard";

With Flyweights, only one copy of “Richard” is stored, and each of the objects share a reference to it. Flyweights can be used in a similar manner to Nullable<T>, with a Value property. They are also implicitly castable to and from T.

string sentence = "The quick brown fox jumps over the lazy dog.";
Flyweight<string> word = "fox";

int n = sentence.IndexOf(word); // implicit cast to string

Documentation, examples and downloads are available from the flyweights project page.

March 2nd, 2008 | 2 Comments