Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 858
TheHat Avatar asked Mar 31 '11 19:03

TheHat


People also ask

Which of the following is true for flyweight design pattern?

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.

Which design pattern does string pool use?

String pool is an example of the Flyweight Design Pattern.

How many participants are available in the flyweight design pattern?

Only 5 colors are available so color property is used to check already existing Circle objects.

What are the applications of flyweight pattern?

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.


2 Answers

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).

like image 191
Anon Avatar answered Nov 15 '22 03:11

Anon


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.

like image 36
Eugen Avatar answered Nov 15 '22 05:11

Eugen