I have used GCMH (the Garbage Collector Magic Hack) for many years. It’s great.
GCMH hooks itself in pre/post-command hooks. It (re)sets its idle timer on every command, which seems to be a good strategy, but also feels a bit too much.
Conversely, all that gc-maybe-mode
does is this:
- With an idle timer (default is 8 seconds), call
garbage-collect-maybe
(from Emacs 28.1 or above) with a factor based on the currentgc-cons-percentage
, so it garbage collects only if needed; - Add hooks to
minibuffer-setup-hook
, to raise the GC cons threshold, and tominibuffer-exit-hook
, to restore the GC cons threshold.
That’s it. It is similar to the GCMH hack, but as a cheap trick.
Also, with a “:before” advice, we can raise the GC cons threshold (gc-maybe-raise-threshold
or gc-maybe-raise-threshold-briefly
) for known costly functions.
When raising the threshold briefly, a “restore” timer is set, so it resets to default values (gc-maybe-restore-threshold
) after an idle delay.
See M-x customize-group RET gc-maybe
for all user options.
(use-package gc-maybe
:vc (:url "https://github.com/bcardoso/gc-maybe/")
:demand t
:config
;; Default values
(setopt gc-maybe-cons-threshold (* 16 1024 1024))
(setopt gc-maybe-cons-percentage 0.2)
(setopt gc-maybe-idle-delay 8)
(setopt gc-maybe-idle-restore 5)
;; Enable mode to set the idle timer and minibuffer hooks
(gc-maybe-mode +1)
;; Optionally log GC data in a buffer
;; (setopt gc-maybe-log-stats-in-buffer t)
;; Advice example
;; (advice-add 'org-ql-select :before #'gc-maybe-raise-threshold-briefly)
)
- GCMH: the Garbage Collector Magic Hack
- [2019-03-11] The original magic Emacs garbage collection hack
- EmacsConf - 2023 - talks - emacs-gc-stats: Does garbage collection actually slow down Emacs?
- [2021-03-07] Opportunistic GC on emacs-devel mailing list