Flyweight : Strings already use String pool : Does it makes sense to pool String objects for Flyweight?
Asked Answered
K

2

5

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?

Kr answered 31/3, 2011 at 19:0 Comment(0)
R
3

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.

Reorder answered 31/3, 2011 at 19:11 Comment(0)
U
7

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 calling intern(), because the latter consumes permgen memory (which is a scarcer resource than normal heap memory).

Unbecoming answered 31/3, 2011 at 19:9 Comment(0)
R
3

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.

Reorder answered 31/3, 2011 at 19:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.