对象池

编程入门 行业动态 更新时间:2024-10-10 15:25:39
本文介绍了对象池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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.

更多推荐

对象池

本文发布于:2023-08-04 21:43:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1299868.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!