endel / NativeWebSocket

🔌 WebSocket client for Unity - with no external dependencies (WebGL, Native, Android, iOS, UWP)
Other
1.27k stars 161 forks source link

Remove unnecessary memory allocations #40

Closed divillysausages closed 2 years ago

divillysausages commented 3 years ago

As DispatchMessageQueue() is called every frame, the unnecessary memory allocations quickly add up and mean that you game gets hit with garbage collection where it's not necessary.

There are 3 changes here:

1) If there's no messages in m_MessageList (most of the time), just return immediately - stops unnecessarily creating and copying an empty list 2) When creating the copy, we just directly pass m_MessageList. This means that messageListCopy is the correct size, and we don't have to use AddRange() (which allocates memory, if I remember correctly - but it definitely does if there's more messages that the default list size) 3) Replace the foreach with a simple for loop, which doesn't allocate any memory

johnou commented 3 years ago

@endel ptal

angelhodar commented 3 years ago

@endel Please take a look at this! @divillysausages Do you know why its needed to call DispatchMessageQueue? Can i just avoid that call?

divillysausages commented 3 years ago

@angelhodar Do you know why its needed to call DispatchMessageQueue? Can i just avoid that call?

On WebGL it does nothing, so if you're only targeting that platform, you can just ignore it. On other platforms it's necessary to get notified of your messages on the main thread - if you don't call it, you'll never receive anything.

I guess you could modify your code to call OnMessage directly in Receive, but I really wouldn't recommend it

endel commented 2 years ago

Thanks a lot for the suggestion @divillysausages, I've applied your change myself because of some recent changes in the Mutex/locking mechanism (Mutex wasn't working on Nintendo Switch)