Does .net sting class support cache/pool mechansism to reduce allocation overhead?
String literals are interned, if that's what you're talking about:
string x = "hello";
string y = "hel" + "lo";
string z = "h" + "ello";
bool a = object.ReferenceEquals(x, y);
bool b = object.ReferenceEquals(y, z);
Both a
and b
are guaranteed to be true.
You can call string.Intern
yourself, too.
However as far as normal strings go (for example, the string object returned by string.Format
), the answer would be no, they're not cached by default. But you could either create your own cache or intern them if you absolutely must. As many strings are short-lived, I suspect that in most cases it's not worth caching.
.NET doesn't do it for you, but we wrote a class with straightforward usage to help do this which is posted in an article over on codeproject.com (includes the implementation of our Single Instance String Store). We use this ourselves internally in Gibraltar to reduce the memory impact, particularly in the Gibraltar.Agent library which is designed to be safely included with our customers' production applications.
The class allows you to consolidate any reference to a string so that each unique string value shares the same copy among all references that have been consolidated, but it still allows that copy to be garbage collected automatically when all of your references to it have been dropped. The small overhead of each WeakReference and the lookup table can be periodically packed.
This works really well for our case, especially, because the Gibraltar.Agent will be handling a large quantity of various strings passing through it as metrics and logging data, some of which may stick around a long time and need many references while others may be used only once and never needed again. It's particularly beneficial when you often recompute the same effective string value because run-time generation of the same value will always end up with a new reference, but the string store can be used to immediately replace that with your "official" copy for that value.
It may not be as useful in some applications such as if most of your strings are in references that aren't as accessible or practical to replace, such as in DataSets.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With