Skip to main content

W0047 - Avoid explicit garbage collection

Warning

-module(main).
-export([warning/0]).

warning() ->
erlang:garbage_collect().
%% ^^^^^^^^^^^^^^^^^^^^^^ 💡 warning: Avoid forcing garbage collection.

Explanation

Erlang manages dynamic memory with a tracing garbage collector. More precisely a per process generational semi-space copying collector. More information about the Erlang garbage collector can be found in the official documentation.

While garbage collection happens automatically, it can manually be triggered via the erlang:garbage_collect/0,1,2. This function forces an immediate garbage collection of the executing process. The function is not to be used unless it has been noticed (or there are good reasons to suspect) that the spontaneous garbage collection will occur too late or not at all. Improper use of this function can seriously degrade the performance of the system.

Instead of forcing garbage collection, try to evaluate what creates a significant amount of garbage which trickes into old heap (and is not collected with minor runs). Refactor your Erlang code to either generate smaller amount of garbage (this also helps with CPU). Start with making a test case reproducing high GC.

If you are certain that explicit garbage collection is needed, you can use add the following to silent this warning:

% elp:ignore W0047 (no_garbage_collect) - Explanation here