对象池 [英] Object Pooling

查看:96
本文介绍了对象池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Pro和Con的维护一个经常使用的对象池并从池中取出一个,而不是创建一个新的。类似于字符串实习,除了它可以用于所有类对象。



例如,它可以被认为是好的,因为它节省了gc时间和对象创建时间。另一方面,如果使用多线程,它可能是一个同步瓶颈,需要显式的释放并引入内存泄漏的可能性。通过捆绑可以回收的内存,它会给垃圾收集器带来额外的压力。

解决方案

除非创建该对象的开销很大,我不打扰。



好处:


  • 创建的对象更少 - 如果对象创建昂贵,这可能很重要。 (典型的例子可能是数据库连接,其中创建包括与服务器建立网络连接,提供认证等。)


    缺点:


    • 更复杂的代码

    • 共享资源=锁定;潜在的瓶颈

    • 违反GC对对象生命周期的期望(大多数对象将会很短)


      你有一个实际的问题,你试图解决,或者是这种推测?我不会考虑做这样的事情,除非你有基准测试/配置文件运行表明存在问题。


      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 except that it will be possible for all class objects.

      For example it can be considered to be good since it saves gc time and object creation time. On the other hand it can be a synchronization bottleneck if used from multiple threads, demands explicit deallocation and introduces possibility of memory leaks. By tying up memory that could be reclaimed, it places additional pressure on the garbage collector.

      解决方案

      Unless the object is expensive to create, I wouldn't bother.

      Benefits:

      • Fewer objects created - if object creation is expensive, this can be significant. (The canonical example is probably database connections, where "creation" includes making a network connection to the server, providing authentication etc.)

      Downsides:

      • More complicated code
      • Shared resource = locking; potential bottleneck
      • Violates GC's expectations of object lifetimes (most objects will be shortlived)

      Do you have an actual problem you're trying to solve, or is this speculative? I wouldn't think about doing something like this unless you've got benchmarks/profile runs showing that there's a problem.

      这篇关于对象池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆