如何编写代码来帮助垃圾收集器 [英] How to write code to help garbage collector

查看:76
本文介绍了如何编写代码来帮助垃圾收集器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在采访中,我遇到一个问题-编写代码时如何帮助垃圾收集器?".

On interview I got a question - "How to help garbage collector when writing code?".

我认为GC确实非常有效,我们不需要使用任何基本的良好代码实践,而是后来补充说,finally子句中的关闭资源可以肯定地帮助GC,但通常对此问题感到惊讶.

In my opinion GC works really good and we don't need to use anything more than basic good code practices, later added that closing resources in finally clause help GC for sure but generally got suprised with such question.

有没有很好的答复?我们需要做一些不可思议的事情来帮助垃圾收集器吗?

Is there a good reply? Do we need to do something incredible to help garbage collector?

推荐答案

问题的措词很奇怪. GC的工作不需要帮助.它可以在施加任何约束的情况下工作,或者如果无法满足约束则失败.

The question is phrased oddly. The GC does not need help with its work. It will work with whatever constraints are imposed on it or fail if the constraints cannot be met.

当然可以更改工作,但这并不是出于减轻GC负担的愿望而进行的-并非人类会为GC的工作感到无聊-而是由于某些别有用心的动机,例如提高整体程序性能.

Of course the work can be altered, but this is not done out of a desire to ease the burden on the GC – it is not a human that can be bored by its work – but due to some ulterior motive, such as improving overall program performance.

这些东西通常被定义为延迟,能耗,吞吐量或内存占用优化.但是,这些并不是程序员关心的唯一指标.简单性和代码可读性也很重要.

These things are normally framed as latency, energy consumption, throughput or memory footprint optimizations. But those are not the only metrics a programmer cares about. Simplicity and code readability also matter.

幼稚的代码可能更具可读性,但性能较低.如果您的目标是易于阅读的代码,则执行复杂的优化以减少GC负担可能会适得其反,因此帮助GC"本身并不是目标.

Naive code can be more readable but less performant. If your goal is easy-to-read code then performing complex optimizations that reduce the GC load could be counter-productive and thus "helping the GC" is not a goal in itself.

现在,如果您的目标是改善某些性能指标,那么某些优化还涉及编写代码,以减少内存管理(分配+ GC)子系统完成的工作.一些可能的优化措施包括避免终结器,发现内存泄漏,减少不必要的分配,避免庞大的Object []数组,调整GC参数,购买更好的硬件并减少对象寿命.适用哪种优化取决于应用程序,并且最好通过分析器,GC日志记录和相关的

Now if your goal is to improve some performance metrics then some optimizations also involve writing code that reduces the work done by the memory management (allocation + GC) subsystem. Some possible optimizations are avoiding finalizers, finding memory leaks, reducing unnecessary allocations, avoiding humongous Object[] arrays, tuning GC parameters, buying better hardware and reducing object lifetimes. Which optimization is applicable depends on the application and can best be figured out with profilers, GC logging and related

这篇关于如何编写代码来帮助垃圾收集器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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