String interning in .Net Framework - What are the benefits and when to use interning

后端 未结 5 824
独厮守ぢ
独厮守ぢ 2020-11-27 05:52

I want to know the process and internals of string interning specific to .Net framework. Would also like to know the benefits of using interning and the sce

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 06:51

    This is an "old" question, but I have a different angle on it.

    If you're going to have a lot of long-lived strings from a small pool, interning can improve memory efficiency.

    In my case, I was interning another type of object in a static dictionary because they were reused frequently, and this served as a fast cache before persisting them to disk.

    Most of the fields in these objects are strings, and the pool of values is fairly small (much smaller than the number of instances, anyway).

    If these were transient objects, it wouldn't matter because the string fields would be garbage collected often. But because references to them were being held, their memory usage started to accumulate (even when no new unique values were being added).

    So interning the objects reduced the memory usage substantially, and so did interning their string values while they were being interned.

提交回复
热议问题