Impact on memory usage - constant strings or resource strings?

Is there an advantage in terms of heap memory when we define string constants in a resource file instead of declaring it as const inside claass?

+4
source share
3 answers

I do not know for sure, but it seems that the const lines will be distributed differently. In particular, they will not be entitled to garbage collection. Thus, it is likely that they have less associated costs than rows loaded from resources. However, the difference is likely to be very small. If you do not have a large number of lines, you will not notice the difference in the use of heap memory.

const used for things that never change. Resource strings are for things that can change. Your decision on how to use should be based on this, and not what place the heap takes.

+4
source

Have you read about string interning ? .NET stores a string cache, so a string exists only once in memory - potentially forever. The constant string will be interned. Strings built dynamically (i.e., using StringBuilder) are not interned.

In response to this question, lines in resource files are not interned. If this is true, and you are loading many resource files with large duplicate lines in your resources, there may be many lines duplicated in memory.

+3
source

In my literals, string.Intern literals, so there are no duplicates and there are no additional allocations for use. I do not think that by default resource strings behave the same.

If this is a concern, you can have your own code for reading and interning strings from resources and checking if this is beneficial for your business.

Side note: constant lines and lines from a resource are usually used for a variety of purposes (one static invariant value of the culture, the other is localized and it is expected that it will be different for different cultures). There must be very good reasons for wrapping localized strings into constants in your code.

+2
source

Source: https://habr.com/ru/post/1443898/


All Articles