After some times trying to figure it out, the best workaround i found to force/invoke Garbage Collector is to create then revoke some data buffers.
Simplest fix on Chrome/Edge was to use:
URL.revokeObjectURL(URL.createObjectURL(new Blob([new ArrayBuffer(5e+7)]))) // 50Mo buffer
BUT then, this would introduce memory leaks on Firefox.
On Firefox, it seems like ObjectURL cannot be revoked without being bound to DOM element. Cannot find anything about it in the spec.
So cross browser solution (Chrome/Edge/Firefox, other browsers not tested), would be:
queueMicrotask(() => { // || >> requestIdleCallback
let img = document.createElement("img");
img.src = window.URL.createObjectURL(new Blob([new ArrayBuffer(5e+7)])); // 50Mo
img.onerror = function() {
window.URL.revokeObjectURL(this.src);
img = null
}
})
Here is a sample working code fixing WebRTC bug:
var i = 1;
function peer() {
var peer = new RTCPeerConnection();
setTimeout(() => {
peer.close();
peer = null;
}, 10);
console.log(i++);
if (!(i % 20)) {
// try to invoke GC on each 20ish iteration
queueMicrotask(() => {
let img = document.createElement("img");
img.src = window.URL.createObjectURL(new Blob([new ArrayBuffer(5e+7)])); // 50Mo or less or more depending as you wish to force/invoke GC cycle run
img.onerror = function() {
window.URL.revokeObjectURL(this.src);
img = null
}
})
}
}
setInterval(peer, 20);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…