Flyweight:字符串已经使用 String pool:为 Flyweight 池化 String 对象是否有意义?
字符串已经在使用享元设计模式。池化公共 String 对象是否有益/高效?因为字符串已经从字符串池中取出了?
Strings are already using Flyweight Design Pattern. Will it be beneficial/performant to pool common String objects. As the Strings will be already pulled from the String pool?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
字符串可以来自很多地方,默认情况下字符串池中只有字符串文字。例如,当您调用 BufferedReader.readLine() 时,它返回的字符串不在字符串池中。
使用 String.intern() 或规范化映射来池化此类字符串是否有意义,取决于您有多少重复项,以及您可以腾出多少内存来减少重复项。
例如,如果您正在读取 XML 文件,规范化元素名称可能非常有用。如果您正在读取地址数据文件,规范化邮政编码和/或城市名称可能会很有用。但是,在这两种情况下,我都会考虑使用 Map 而不是调用 intern(),因为后者会消耗 permgen 内存(这是比普通堆内存更稀缺的资源) )。
Strings can come from many places, and by default only string literals are in the string pool. For example, when you call
BufferedReader.readLine()
, the string that it returns is not in the string pool.Whether it makes sense to pool such strings, either using
String.intern()
or a canonicalizing map, depends on how much duplication you have, and how much memory you can spare to reduce that duplication.For example, if you're reading an XML file, it might be very useful to canonicalize element names. If you're reading a file of address data, it might be useful to canonicalize zip codes and/or city names. However, in both cases I'd look at using a
Map
rather than callingintern()
, because the latter consumes permgen memory (which is a scarcer resource than normal heap memory).如果没有有关您的系统的任何其他信息,我会说创建特定用途的字符串池将属于过早优化类别。如果您的系统确实需要大量的 String 操作,并且分析显示 String 对象是发生主要垃圾收集的原因,那么我建议将 StringBuilder 作为替代品,并深入了解使用 String 的最佳实践。为它们创建缓存。
Without any other info about your system, I would say that creating a specific purpose pool of Strings would fall in the premature optimization category. If your system is indeed very String operation heavy and profiling shows that String objects are the reason that major garbage collections occur, then I would recommend looking at StringBuilder as a replacement, as well as understanding in depth the best practices of working with Strings, instead of creating a cache for them.