mirror of
https://github.com/qbittorrent/qBittorrent.git
synced 2025-12-19 15:07:22 -06:00
Avoid unnecessary memory allocation/relocation
This commit is contained in:
@@ -46,6 +46,10 @@ Connection::Connection(QTcpSocket *socket, IRequestHandler *requestHandler, QObj
|
||||
{
|
||||
m_socket->setParent(this);
|
||||
|
||||
// reserve common size for requests, don't use the max allowed size which is too big for
|
||||
// memory constrained platforms
|
||||
m_receivedData.reserve(1024 * 1024);
|
||||
|
||||
// reset timer when there are activity
|
||||
m_idleTimer.start();
|
||||
connect(m_socket, &QIODevice::readyRead, this, [this]()
|
||||
@@ -66,7 +70,18 @@ Connection::~Connection()
|
||||
|
||||
void Connection::read()
|
||||
{
|
||||
m_receivedData.append(m_socket->readAll());
|
||||
// reuse existing buffer and avoid unnecessary memory allocation/relocation
|
||||
const qsizetype previousSize = m_receivedData.size();
|
||||
const qint64 bytesAvailable = m_socket->bytesAvailable();
|
||||
m_receivedData.resize(previousSize + bytesAvailable);
|
||||
const qint64 bytesRead = m_socket->read((m_receivedData.data() + previousSize), bytesAvailable);
|
||||
if (Q_UNLIKELY(bytesRead < 0))
|
||||
{
|
||||
m_socket->close();
|
||||
return;
|
||||
}
|
||||
if (Q_UNLIKELY(bytesRead < bytesAvailable))
|
||||
m_receivedData.chop(bytesAvailable - bytesRead);
|
||||
|
||||
while (!m_receivedData.isEmpty())
|
||||
{
|
||||
@@ -116,7 +131,7 @@ void Connection::read()
|
||||
resp.headers[HEADER_CONNECTION] = u"keep-alive"_s;
|
||||
|
||||
sendResponse(resp);
|
||||
m_receivedData = m_receivedData.mid(result.frameSize);
|
||||
m_receivedData.remove(0, result.frameSize);
|
||||
}
|
||||
break;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user