How does java implement flyweight pattern for stri

2019-01-14 07:10发布

If you have two instances of a String, and they are equal, in Java they will share the same memory. How is this implemented under the hood?

EDIT: My application uses a large number of String objects, many of which are identical. What is the best way to make use of Java String constant pool, as to avoid creating custom flyweight implementation?

7条回答
女痞
2楼-- · 2019-01-14 08:15

If your identical Strings come from a fixed set of possible values, then a Type-Safe Enumeration is what you want here. Not only will it reduce your String count, but it will make for a more solid application. Your whole app will know this String has semantics attached to it, maybe even some convenience methods.

My favorite optimizations are always the ones that can be defended as making the code better, not just faster. And 9 times out of 10, replacing a String with a concrete type leads to more correct and self-documenting code.

查看更多
登录 后发表回答