I made a test program to see how well Flyweight would work in Java. For the record, I will describe my results here. Ymmv
1) If you have several fields in your objects, you will save some processor by combining them into one int or long. This is a pain in regards to programs and errors, but it is several percent faster, because access to several arrays is more expensive than bit manipulation. Moreover, the number of fields is increasing.
2) For small instances (4 status bytes), it will run about 25% slower, and then it will store the instance directly. But, ONLY if you do not create a new instance for each receipt. This is the real problem. The need to create a new instance at each receipt is very expensive; in this case, it is not 25% slower, but 500% slower!
3) I see two ways to save instance creation in get:
A) Your get method populates an existing instance instead of creating a new one. In other words, you pass the result object as input to the get method.
B) You use immutable instances, cache them, and return the cached instance from get. This is only useful if your list index is significant and you expect to reuse the same values ββin your list. If you do this, you can also keep a direct link to your cached instance in your collection, and not to some state, because then you still pay only 4 bytes per instance for reference. In this case, your state must be 2 bytes or less before it makes sense to store the state instead of a link.
So, as the final answer, the reason why there is no universal library for Flyweight there is that it pays only under certain conditions, otherwise it really is not worth it.
source share