Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS websocket memory issue in React Native

We're experiencing a memory leak when using the websocket blob implementation in React Native, and can't quite locate the issue.

Using Xcode Instruments we can see that the issue most likely happens in the way the framework handles binary messages in RCTSRWebSocket.m or perhaps later in the call tree at RCTWebSocketModule.m

Anyone with Object-C Skills who are able to see why some memory (presumably alocated to the received messages) aren't being properly released ?

Link to Github issue

Memory usage

Debug Info

Call tree

like image 747
Steffen Christensen Avatar asked Nov 20 '17 15:11

Steffen Christensen


2 Answers

The issue can finally be resolved. After digging around in the implementation of WebSockets and especially the blobs, I found that all blobs will stay in memory as long as they aren't being directly closed.

This means that after you're done with the received data, you should close the Blob like this:

ws.onmessage = function (e) {
  // Do whatever with the data through e.data.
  const data = e.data;
  // When you are done with the received data, you must close the Blob:
  e.data.close();
};
like image 151
Steffen Christensen Avatar answered Nov 13 '22 22:11

Steffen Christensen


Maybe it's me but it seems the frameData is copied? It's NSData so a reference type and it's not clear to me why a copy is needed? It is necessary because it's changed afterwards and you want the original to remain the same? Otherwise copying is completely unnecessary and perhaps this helps things a bit? If all the data it's reading is copied and perhaps retained somehow in the '_handleMessage' function it can lead to big memory allocations.

So my first attempts would be:

  1. Simply send frameData to and don't copy it:

[self _handleMessage:frameData];

  1. Check if you can perhaps forcefully set the frameData to nil once you're done with it in the _handleMessage function.
like image 33
Bob de Graaf Avatar answered Nov 13 '22 21:11

Bob de Graaf