uNetworking / uWebSockets.js

μWebSockets for Node.js back-ends :metal:
Apache License 2.0
7.95k stars 570 forks source link

app.publish is faster than ws.send? #998

Closed 00sos00 closed 9 months ago

00sos00 commented 9 months ago

I am currently working on a game, and I am sending the info of all 100 players to each other.

The way I am currently doing this is by doing

for (ws in wsArr) {
    ws.send(data, true); // data is around 2000 bytes big
}

I benchmarked this loop and found that it takes around 12ms.

But when I switched to this

app.publish('global', data, true) // same size of data

It only took around 3ms

So what's the catch here?

uNetworkingAB commented 9 months ago

Why would there be a catch?

00sos00 commented 9 months ago

Why would there be a catch?

Meant to say what's the reason behind this

uNetworkingAB commented 9 months ago

It's the same question just worded differently ;)

Pub/sub is faster because it's designed to be faster for Pub/sub. It's a misconception that it would be the same as a for loop.

Shitty libraries implement it as just a for loop. But you probably want to benchmark end to end.

uNetworkingAB commented 9 months ago

The websocket benchmark of https://bun.sh uses Pub/sub thats why it performs way better

00sos00 commented 9 months ago

benchmark

Interesting, does pub/sub use .send under the hood? And if so, would it be possible for me to design a similar architecture but with a custom message for each client?

uNetworkingAB commented 9 months ago

Typically these "IO games" send the same message to everyone but the sender, for every client.

00sos00 commented 9 months ago

Typically these "IO games" send the same message to everyone but the sender, for every client.

Depends on the game. Some games send only entities that are within a certain distance from each player

uNetworkingAB commented 9 months ago

It's the same. You just divide the game world into squares and have those be their own topic. Still overall same idea

00sos00 commented 9 months ago

It's the same. You just divide the game world into squares and have those be their own topic. Still overall same idea

Oh that's clever, never thought of splitting world just for sending messages. I always thought of it as a way to reduce collision checks

00sos00 commented 9 months ago

Is there a limit to how many topics I could create? I am planning having a 21x21 grid which is around 400 topics

uNetworkingAB commented 9 months ago

You can have many many topics but always good to benchmark