I am working on an application that reads lots of data from the network and puts it in a grid. I noticed that I could save some memory by reusing existing strings instead of always using the new strings that came off the wire. So here is the class that I wrote to accomplish that. It is simple and it works. But I was wondering if this had a name and, of course, if the code could be improved. One thing that I don't like is that I'm storing two references to each string.
public class StringCollection
{
private Dictionary<string, string> lookup_ = new Dictionary<string, string>();
public string Reuse(string s)
{
if (s == null)
{
return null;
}
string existing;
if (lookup_.TryGetValue(s, out existing))
{
return existing;
}
else
{
lookup_.Add(s, s);
return s;
}
}
public void Clear()
{
lookup_.Clear();
}
public int Count { get { return lookup_.Count; } }
}