Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.net string cache/pool

Tags:

c#

Does .net sting class support cache/pool mechansism to reduce allocation overhead?

like image 324
Maanu Avatar asked Dec 22 '22 00:12

Maanu


2 Answers

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.

like image 116
Jon Skeet Avatar answered Jan 04 '23 05:01

Jon Skeet


.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.

like image 27
Rob Parker Avatar answered Jan 04 '23 07:01

Rob Parker