justintv / Twitch-API

A home for details about our API
www.twitch.tv
1.72k stars 381 forks source link

Gigabytes of memory leaks in twitch embeds crash tabs #679

Open ubershmekel opened 7 years ago

ubershmekel commented 7 years ago

Removing an element with a twitch embed will leak its entire memory usage. Even if there is no listener.

I've made an example with two buttons. You can click the "Play" button to show a stream, get a heap snapshot, then hit "remove" to see the new memory usage. Rinse and repeat to see you lose 90MB each time.

https://jsfiddle.net/ubershmekel/kew80vbj/2/

For posterity - this is the full code in that snippet:

HTML:

<script src= "https://player.twitch.tv/js/embed/v1.js"></script>
<button id="playit">Play</button>
<button id="removeit">Remove</button>

JS:

document.getElementById('playit').onclick = function() {
  var div = document.createElement('div');
  div.id="PLAYER_DIV_ID";
  document.body.append(div);
  var options = {
      width: 854,
      height: 480,
      channel: "twitchpresents",
  };
  var player = new Twitch.Player("PLAYER_DIV_ID", options);
}

document.getElementById('removeit').onclick = function() {
  var x = document.querySelectorAll('#PLAYER_DIV_ID')[0];
  x.parentElement.removeChild(x);
}

Alongside that 4 twitch embeds leak about 1 MB of memory per minute. That means 1.4GB per day just for running at all without replacing any stream.

This has caused me to write all kinds of hard-reloads in my webapp: http://ubershmekel.github.io/twitchn/?panels=4&game=Heroes+of+the+Storm

But it still doesn't prevent Chrome from crashing once in a while because the process itself is having trouble cleaning up some of the things that are happening in a twitch embed.

Please help.

Tested on Chrome 56.0.2924.87 (64-bit), Windows 10.0.14393 Build 14393