简体   繁体   English

对内存使用的影响 - 常量字符串或资源字符串?

[英]Impact on memory usage - const strings or resource strings?

当我们在资源文件中定义字符串常量而不是在claass中声明为const时,在堆内存占用方面是否有优势?

I don't know for certain, but it seems like const strings would be allocated differently. 我不确定,但似乎const字符串的分配方式不同。 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. const用于永不改变的事物 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. .NET保留字符串的缓存,使得字符串在内存中只存在一次 - 可能永远存在。 Constant string will be interned. 常量字符串将被实现。 Strings built dynamically (ie with a StringBuilder) are not interned. 动态构建的字符串(即使用StringBuilder)不会被实现。

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. 对我的knowlwdge字符串文字进行实习(String.Intern),因此没有重复项,也没有额外的使用分配。 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. 应该有很好的理由将可本地化的字符串迁移到代码中的常量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM