Object Pooling in Java

后端 未结 7 1663
鱼传尺愫
鱼传尺愫 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:45

    It entirely depends on how expensive your objects are to create, compared to the number of times you create them... for instance, objects that are just glorified structs (e.g. contain only a couple of fields, and no methods other than accessors) can be a real use case for pooling.

    A real life example: I needed to repetitively extract the n highest ranked items (integers) from a process generating a great number of integer/rank pairs. I used a "pair" object (an integer, and a float rank value) in a bounded priority queue. Reusing the pairs, versus emptying the queue, throwing the pairs away, and recreating them, yielded a 20% performance improvement... mainly in the GC charge, because the pairs never needed to be reallocated throughout the entire life of the JVM.

    0 讨论(0)
提交回复
热议问题