Skip to content

Commit

Permalink
Core/Network: Optimize CPU consumption by decreasing heap allocations.
Browse files Browse the repository at this point in the history
  • Loading branch information
walkline committed May 25, 2024
1 parent d8240fb commit 9df200f
Showing 1 changed file with 32 additions and 28 deletions.
60 changes: 32 additions & 28 deletions src/server/game/Server/WorldSocket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -81,40 +81,44 @@ void WorldSocket::CheckIpCallback(PreparedQueryResult result)
bool WorldSocket::Update()
{
EncryptablePacket* queued;
MessageBuffer buffer(_sendBufferSize);
while (_bufferQueue.Dequeue(queued))
if (_bufferQueue.Dequeue(queued))
{
ServerPktHeader header(queued->size() + 2, queued->GetOpcode());
if (queued->NeedsEncryption())
_authCrypt.EncryptSend(header.header, header.getHeaderLength());

if (buffer.GetRemainingSpace() < queued->size() + header.getHeaderLength())
// Allocate buffer only when it's needed but not on every Update() call.
MessageBuffer buffer(_sendBufferSize);
do
{
QueuePacket(std::move(buffer));
buffer.Resize(_sendBufferSize);
}
ServerPktHeader header(queued->size() + 2, queued->GetOpcode());
if (queued->NeedsEncryption())
_authCrypt.EncryptSend(header.header, header.getHeaderLength());

if (buffer.GetRemainingSpace() >= queued->size() + header.getHeaderLength())
{
buffer.Write(header.header, header.getHeaderLength());
if (!queued->empty())
buffer.Write(queued->contents(), queued->size());
}
else // single packet larger than 4096 bytes
{
MessageBuffer packetBuffer(queued->size() + header.getHeaderLength());
packetBuffer.Write(header.header, header.getHeaderLength());
if (!queued->empty())
packetBuffer.Write(queued->contents(), queued->size());
if (buffer.GetRemainingSpace() < queued->size() + header.getHeaderLength())
{
QueuePacket(std::move(buffer));
buffer.Resize(_sendBufferSize);
}

QueuePacket(std::move(packetBuffer));
}
if (buffer.GetRemainingSpace() >= queued->size() + header.getHeaderLength())
{
buffer.Write(header.header, header.getHeaderLength());
if (!queued->empty())
buffer.Write(queued->contents(), queued->size());
}
else // single packet larger than buffer size
{
MessageBuffer packetBuffer(queued->size() + header.getHeaderLength());
packetBuffer.Write(header.header, header.getHeaderLength());
if (!queued->empty())
packetBuffer.Write(queued->contents(), queued->size());

delete queued;
}
QueuePacket(std::move(packetBuffer));
}

delete queued;
} while (_bufferQueue.Dequeue(queued));

if (buffer.GetActiveSize() > 0)
QueuePacket(std::move(buffer));
if (buffer.GetActiveSize() > 0)
QueuePacket(std::move(buffer));
}

if (!BaseSocket::Update())
return false;
Expand Down

0 comments on commit 9df200f

Please sign in to comment.