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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With