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

后端 未结 5 820
独厮守ぢ
独厮守ぢ 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:54

    Interned strings have the following characteristics:

    • Two interned strings that are identical will have the same address in memory.
    • Memory occupied by interned strings is not freed until your application terminates.
    • Interning a string involves calculating a hash and looking it up in a dictionary which consumes CPU cycles.
    • If multiple threads intern strings at the same time they will block each other because accesses to the dictionary of interned strings are serialized.

    The consequences of these characteristics are:

    • You can test two interned strings for equality by just comparing the address pointer which is a lot faster than comparing each character in the string. This is especially true if the strings are very long and start with the same characters. You can compare interned strings with the Object.ReferenceEquals method, but it is safer to use the string == operator because it checks to see if the strings are interned first.

    • If you use the same string many times in your application, your application will only store one copy of the string in memory reducing the memory required to run your application.

    • If you intern many different strings this will allocate memory for those strings that will never be freed, and your application will consume ever increasing amounts of memory.

    • If you have a very large number of interned strings, string interning can become slow, and threads will block each other when accessing the interned string dictionary.

    You should use string interning only if:

    1. The set of strings you are interning is fairly small.
    2. You compare these strings many times for each time that you intern them.
    3. You really care about minute performance optimizations.
    4. You don't have many threads aggressively interning strings.

提交回复
热议问题