Object Pooling in Java

后端 未结 7 1664
鱼传尺愫
鱼传尺愫 2020-12-29 08:19

What are the pro\'s and con\'s of maintaining a pool of frequently used objects and grab one from the pool instead of creating a new one. Something like string interning exc

7条回答
  •  生来不讨喜
    2020-12-29 08:43

    Pooling will mean that you, typically, cannot make objects immutable. This leads to defencive copying so you ultimately wind up making many more copies than you would if you just made a new immutable object.

    Immutability is not always desirable, but more often than not you will find that things can be immutable. Making them not immutable so that you can reuse them in a pool is probably not a great idea.

    So, unless you know for certain that it is an issue don't bother. Make the code clear and easy to follow and odds are it will be fast enough. If it isn't then the fact that the code is clear and easy to follow will make it easier to speed it up (in general).

提交回复
热议问题