Make use of malloc_trim() to hand memory back to the system
JavaScript programs (especially long-lived ones like gnome-shell) can have high memory usage over short timeframes, where the exact amount of memory used can hardly be controlled due to JS being garbage collected. This can lead to gjs having to allocate lots of memory on the heap to allow for some short high-memory requirement, but then never handing that back to the system even after garbage collection.
That's because malloc()
and free()
are highly optimized and they silently keep allocated memory around after it's been free()
'd, which will allow for much quicker results on subsequent calls to malloc()
.
This unused memory can be handed back to the system by calling malloc_trim()
.
It probably makes sense for gjs to make use of malloc_trim()
, especially once the Big Hammer is removed. Right now, with GC running every 10 seconds, the heap probably won't ever grow to the point where gjs is using a significant amount of system RAM. But once GC runs less often again, and gjs temporarily (between two GC cycles) needs lots of memory, it might make sense to call malloc_trim()
after that GC freed lots or memory (this would likely need some kind of heuristic, because over-eager calling of malloc_trim()
also seems like a bad idea).