Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Impact on memory usage - const strings or resource strings?

Tags:

c#

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

like image 790
Otávio Décio Avatar asked Nov 04 '12 02:11

Otávio Décio


3 Answers

I don't know for certain, but it seems like const strings would be allocated differently. In particular, they won't be eligible for garbage collection. So it's likely that they have less overhead associated with them than do strings loaded from resources. The difference, however, is likely to be very small. Unless you have a huge number of strings, you're not going to notice a difference in your heap memory usage.

const is used for things that never change. Resource strings are for things that are likely to change. Your decision on which to use should be based on that, not on which one takes more space on the heap.

like image 139
Jim Mischel Avatar answered Oct 24 '22 06:10

Jim Mischel


Have you read about string interning? .NET keeps a cache of strings such that a string exists only once in memory-- potentially forever. Constant string will be interned. Strings built dynamically (i.e. with a StringBuilder) are not interned.

According to an answer this question, strings in resource files are not interned. If this is true, and you load many resource files with large duplicate strings in their resources, there could be lots of strings duplicated in memory.

like image 31
Paul Williams Avatar answered Oct 24 '22 04:10

Paul Williams


To my knowlwdge string literals are interned (String.Intern) so there is no duplicates and no extra allocations on usage. I don't think by default resource strings behave the same way.

If this is a concern you can have your own code reading and interning strings from resources and verify if it is beneficial for your case.

Side note: constant strings and strings from resource are normally used for very different purposes (one static culture invariant values, the other - localizable and expected to be different for different cultures). There should be very good reasons to migrate localizable strings to be constants in the code.

like image 3
Alexei Levenkov Avatar answered Oct 24 '22 04:10

Alexei Levenkov