My friend and I are making a node.js game, and we have been testing CPU. After profiling, it was determined that this process called zlib is sucking most of the CPU/RAM.
3 clients connected to a game is fine, but when 12~13 players are connected it uses 58% where zlib is using about 30% of this CPU.
inclusive self name ticks total ticks total 64775 58.5% 64775 58.5% /lib/x86_64-linux-gnu/libc-2.19.so 25001 22.6% 224 0.2% LazyCompile: *callback zlib.js:409 //this one is a different zlib 7435 6.7% 82 0.1% LazyCompile: ~callback zlib.js:409
Is there any way to decrease the CPU usage from this? Or is there a reason why it is increasing so much?
I have done some reading and I am told it is from socket.io, so here is our section of socket sending most of the data:
for (var i = 0; i < users.length; i++) {
if (u.room == users[i].room && users[i].x + users[i].radius >= u.x - u.screenWidth / 2 - 20 && users[i].x - users[i].radius <= u.x + u.screenWidth / 2 + 20 && users[i].y + users[i].radius >= u.y - u.screenHeight / 2 - 20 && users[i].y - users[i].radius <= u.y + u.screenHeight / 2 + 20) {
if (users[i].id == u.id) {
visiblePlayers.push({
x: users[i].x,
y: users[i].y,
angle: users[i].angle,
hue: users[i].hue,
radius: users[i].radius,
squeeze: users[i].squeeze,
name: users[i].name,
dead: users[i].dead,
isPlayer: true,
kills: users[i].kills
});
} else {
visiblePlayers.push({
x: users[i].x,
y: users[i].y,
angle: users[i].angle,
hue: users[i].hue,
radius: users[i].radius,
squeeze: users[i].squeeze,
name: users[i].name,
dead: users[i].dead
});
}
// SEND DYING INFO: (FOR OFFLINE ANIMATION):
if (users[i].dying) {
visiblePlayers[visiblePlayers.length - 1].dying = true;
}
}
}
var visibleEnergy = [];
for (var i = 0; i < energies.length; i++) {
if (u.firstSend || (energies[i].updated && energies[i].room == u.room)) {
var anim = energies[i].animate;
if (u.firstSend)
anim = true;
visibleEnergy.push({
x: energies[i].x,
y: energies[i].y,
radius: energies[i].radius,
index: i,
animate: anim,
hue: energies[i].hue,
room: energies[i].room
});
}
}
// SEND PLAYER UPDATES TO CLIENTS:
sockets[u.id].emit('serverTellPlayerMove', visiblePlayers,
visibleEnergy);
zlib
is used to compress/extract data being sent to and from the server at lower level than your code. So it's not really your code that's at fault; it's more a configuration thing. There are certainly things to review in your code too, and we'd be happy to suggest some things, but changing your code won't change low-level data compression is handled since data is still sent the same way. \$\endgroup\$