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?
Apply the Flyweight pattern when all of the following are true: An application uses a large number of objects. Storage costs are high because of the sheer quantity of objects. Most object state can be made extrinsic.
String pool is an example of the Flyweight Design Pattern.
Only 5 colors are available so color property is used to check already existing Circle objects.
Flyweight design pattern is used when we need to create a lot of Objects of a class. Since every object consumes memory space that can be crucial for low memory devices, such as mobile devices or embedded systems, flyweight design pattern can be applied to reduce the load on memory by sharing objects.
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).
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.
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