.net string cache / pool

Does the .net sting class support a cache / channel pool class to reduce distribution costs?

+4
source share
2 answers

String literals are interned if this is what you are 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 guaranteed to be true.

You can also call string.Intern .

However, as far as normal lines go (for example, the string object returned by string.Format ), the answer will be negative, they are not cached by default. But you can either create your own cache, or set them if you absolutely need it. Since many lines are short-lived, I suspect that in most cases this should not be cached.

+6
source

.NET does not do this for you, but we wrote a class with simple use to help do this, which is published in an article on codeproject. com (includes the implementation of our Single Instance String Store). We use this on our own inside Gibraltar to reduce memory impact, especially in the Gibraltar.Agent library, which is designed to safely integrate customers into our production applications.

The class allows you to consolidate any link to a string so that each unique string value shares the same copy among all the links that have been merged, but still allows you to automatically copy this garbage when all your links to it have been dropped. The small overhead of each WeakReference and lookup tables may be periodically packed.

This works very well for our case, especially because Gibraltar.Agent will process a large number of different lines passing through it, like indicators and registration data, some of which can take a long time and need many links, others can be used only one times and no longer needed. This is especially useful when you often repeat the same effective string value, because generating the runtime of the same value will always contain a new link, but the string store can be used to immediately replace this β€œofficial” copy for that value.

This may not be so useful in some applications, for example, if most of your lines are in links that are inaccessible or practically replaceable, for example, in DataSets.

+5
source

All Articles