patterncsharpModerate
Reusing strings read from I/O
Viewed 0 times
reusingfromstringsread
Problem
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 lookup_ = new Dictionary();
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; } }
}Solution
You might want to look into string interning:
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.
While it has some memory-related side-effects, you could avoid having to build up a dictionary like this and throw away allocated strings to keep it updated.
The common language runtime conserves string storage by maintaining a table, called the intern pool, that contains a single reference to each unique literal string declared or created programmatically in your program. Consequently, an instance of a literal string with a particular value only exists once in the system.
While it has some memory-related side-effects, you could avoid having to build up a dictionary like this and throw away allocated strings to keep it updated.
Context
StackExchange Code Review Q#5460, answer score: 10
Revisions (0)
No revisions yet.