On interview I got a question - "How to help garbage collector when writing code?".
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?
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.
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.
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.
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