I'm curious about how JavaScript manages memory fragmentation. Does it take any steps to combat it, or is it left unaddressed? Specifically, does JavaScript's garbage collection have a compaction feature similar to what C# offers? Also, is it possible to encounter a fatal out-of-memory error even when there seems to be free memory available due to fragmentation?
2 Answers
It really varies depending on the runtime. V8 and Spidermonkey both perform some compaction, while JavaScriptCore, used in Safari, doesn’t seem to. Each of these engines has detailed blog entries about how their garbage collection works.
Modern JavaScript engines, like V8, utilize a mark-sweep-compact algorithm for garbage collection. This means that after it sweeps up unused memory, it actually compacts it to minimize fragmentation. If you want to dive deeper, check out the V8 blog for a detailed explanation!
Thanks, this is exactly the info I needed. Though, it’s more fun to say "THE SCAVENGER EVACUATES" instead of just the compactor moves! All the jargon can make it hard to find stuff on Google, haha.

Yeah, it’s interesting how each language has its own virtual machine. Keeps things diverse!