简体   繁体   中英

How to release the memory of XMLHttpRequest in javascript?

I am using XMLHttpRequest to download the file of size 750mb as arraybuffer. The problem is that after downloading the file, the memory is not released to the os even after deleting the XMLHttpRequest object. My sample code is

<!DOCTYPE html>
<html>
<body>

<div id="demo">
<button type="button" onclick="loadXMLDoc()">load the file</button>
<button type="button" onclick="clear()">clear</button>
</div>

<script>
var xhttp = null;
function loadXMLDoc() {
    if(xhttp == null)
        xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      console.log(xhttp.response);
      delete xhttp;
      xhttp = null;

    }
  };
    xhttp.open("GET", "http://192.168.1.104/gltf/bmw/buffer.bin", true); //buffer.bin is 750 mb

    xhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhttp.responseType = 'arraybuffer';
    xhttp.send();
}

function clear()
{
    delete xhttp;
    xhttp = null;


}

</script>

</body>
</html>

1) is this the right way to delete the XMLHttpRequest object? 2) How to make the XMLHttpRequest to release the memory back to the os? 在此处输入图片说明

Thanks

Not exactly. delete <variable name> even looks confusing(and I'm surprised it works without throwing an error). <variable> = null is correct approach in general. But in your case it should not make a difference.

JS implements own memory management . Garbage collector will free memory once related variable is not used by anyone else.

The thing is Garabge Collector is not running continuously. Rather it's called from time to time. Try clicking "Collect Garbage" button in Developer Tools. This will call GC immediately. 开发人员工具-启动垃圾收集

This is not a solution rather a way to investigate if memory can be freed or it cannot because of referencing to your data from somewhere.

我发现问题出在“ console.log()”。如果我注释掉console.log行,则内存释放回操作系统。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM