Java Object Reuse

2020-02-10 12:32发布

Should Java Objects be reused as often as it can be reused ? Or should we reuse it only when they are "heavyweight", ie have OS resources associated with it ?

All old articles on the internet talk about object reuse and object pooling as much as possible, but I have read recent articles that say new Object() is highly optimized now ( 10 instructions ) and Object reuse is not as big a deal as it used to be.

What is the current best practice and how are you people doing it ?

标签: java
8条回答
仙女界的扛把子
2楼-- · 2020-02-10 13:26

If you use them very intensively and the construction is costly, you should try to reuse them as much as you can.

If your objects are very small, and cheap to create ( like Object ) you should create new ones.

For instance connections database are pooled because the cost of creating a new one is higher than those of creating .. mmhh new Integer for instance.

So the answer to your question is, reuse when they are heavy AND are used often ( it is not worth to pool a 3 mb object that is only used twice )

Edit:

Additionally, this item from Effective Java:Favor Immutability is worth reading and may apply to your situation.

查看更多
再贱就再见
3楼-- · 2020-02-10 13:26

The rule of thumb should be to use your common sense and reuse objects when their creation consumes significant resources such as I/O, network traffic, DB connections, etc...

If it's just creating a new String(), forget about the reuse, you'll gain nothing from it. Code readability has higher preference.

查看更多
登录 后发表回答