Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

javascript - How to clear closed RTCPeerConnection >> [with WORKAROUND]

This is the old famous Chromium bug: https://bugs.chromium.org/p/chromium/issues/detail?id=825576

The error is: Failed to construct 'RTCPeerConnection': Cannot create so many PeerConnections

Now because Edge is based on Chromium, not only Chrome is affected by this bug making things even worst.

We need to find a way to force Garbage Collector cycle.

I posted my current workaround but i'd be glad to find a better workaround, if any...?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...