News for hackers. Stuff that matters.
Re:So We've Got a Memory Leak by Jasper_ on Saturday May 11, 2024 @01:21PM (#40329418)
Uncollectable reference cycles are shockingly easy to make in JS, especially with React. A classic example:

    function closure() {
        var smallObject = 3;
        var largeObject = Array(1000000);

        function longLived() { return smallObject; }
        function shortLived() { return largeObject; }
        shortLived(); return longLived;
    }
Will keep largeObject alive.
Re:So We've Got a Memory Leak by AgentME on Saturday May 11, 2024 @03:34PM (#40330144)
This isn't an uncollectable reference cycle. It's true that with this code in most/all JS engines, if there's a reference to the function `longLived` then `largeObject` will be kept in memory, but reference cycles are collectable in standard garbage collection systems. Both of the values will be garbage-collectable once no outside references to `longLived` still exist. Pure reference counting systems (Rust Rc, C++ shared_ptr, etc) are the kind of system that fail to automatically handle cycles.

You could test this with your code by setting a FinalizationRegistry to log when they're both finalized, unset any outside reference to `longLived`, and then do something to force a GC (like run Node with --expose-gc and call `global.gc()`, or just allocate a big Uint8Array).

Re:So We've Got a Memory Leak by cobbal on Saturday May 11, 2024 @01:39PM (#40329522)
Is this a property of JavaScript or the engine running it? This feels like something a sufficiently-smart™ closure implementation should be able to prevent.
Re:So We've Got a Memory Leak by Jasper_ on Saturday May 11, 2024 @02:04PM (#40329659)
This is an artifact of V8's GC. Effectively, largeObject and smallObject are tracked together, as a unit. Splitting it out into two separate records increases average memory usage. They keep saying they want to fix it eventually, but it's been this way for 10+ years at this point.

You really do have to know the quirks of what you're targeting.

Re:So We've Got a Memory Leak by Dylan16807 on Sunday May 12, 2024 @12:29AM (#40332287)
> sufficiently-smart™

Well, the reference lua implementation handles this case fine, and it's a solid but not at all smart™ codebase.

Re:So We've Got a Memory Leak by kevingadd on Saturday May 11, 2024 @01:53PM (#40329600)
JS runtimes are allowed to optimize this out, IIRC, and will often do so.
Re:So We've Got a Memory Leak by moonchild on Saturday May 11, 2024 @11:26PM (#40332096)
Geez! Didn't henry baker warn against implementing closures this way decades ago? This is an implementation bug—the code is fine.