How do I create a memory leak in JavaScript?

前端 未结 6 1666
南笙
南笙 2021-01-31 03:34

I would like to understand what kind of code causes memory leaks in JavaScript and created the script below. However, when I run the script in Safari 6.0.4 on OS X the memory co

6条回答
  •  天涯浪人
    2021-01-31 04:16

    2020 Update:

    Most CPU-side memory overflow is no longer working on modern v8 engine based browser. However, we can overflow the GPU-side memory by running this script

    // Initialize canvas and its context
    window.reallyFatCanvas = document.createElement('canvas');
    let context = window.reallyFatCanvas.getContext('2d');
    
    // References new context inside context, in loop.
    function leakingLoop() {
        context.canvas.width = document.body.clientWidth;
        context.canvas.height = document.body.clientHeight;
        const newContext = document.createElement('canvas').getContext('2d');
        context.context = newContext;
        context.drawImage(newContext.canvas, 0, 0);
        
        // The new context will reference another context on the next loop
        context = newContext;
    }
    
    // Use interval instead of while(true) {...}
    setInterval(leakingLoop,1);
    

    EDIT: I rename every variables (and constants) so it makes a lot of sense. Here is the explanation.

    Based on my observation, canvas context seems sync with Video Memory. So if we put reference of a canvas object which also reference another canvas object and so on, the Video RAM fills a lot more than DRAM, tested on microsoft edge and chrome.

    This is my third attempt of screenshot:

    I have no idea why my laptop always freeze seconds after taking screenshot while running this script. Please be careful if you want to try that script.

提交回复
热议问题