@@ -70,8 +70,7 @@ TcpConnection::TcpConnection(asio_compat::io_service_t& ioSer
7070 " Reserving memory for receive and send buffers as: " << DEFAULT_RESERVED_SIZE << " bytes" );
7171#endif
7272
73- m_receiveBuffer.reserve (DEFAULT_RESERVED_SIZE );
74- m_messageBuffer.reserve (DEFAULT_RESERVED_SIZE );
73+ m_messageBuffer.reserve (DEFAULT_LARGE_RESERVED_SIZE );
7574}
7675
7776boost_tcp_t ::socket& TcpConnection::Socket ()
@@ -301,11 +300,9 @@ void TcpConnection::StartAsyncRead(const defs::connection_t& endPoint)
301300
302301void TcpConnection::AsyncReadFromSocket (size_t amountToRead)
303302{
304- m_receiveBuffer.resize (amountToRead);
305-
306303 // Wrap in strand just to be safe in case of multiple threads running the IO service.
307304 boost_asio::async_read (m_socket,
308- boost_asio::buffer (m_receiveBuffer),
305+ boost_asio::buffer (m_receiveBuffer. data (), amountToRead ),
309306 asio_compat::wrap (m_strand,
310307 boost::bind (&TcpConnection::ReadComplete,
311308 shared_from_this (),
@@ -351,6 +348,7 @@ void TcpConnection::ReadComplete(const boost_sys::error_code& error, size_t byte
351348 // back_inserter solution.
352349 auto const currentSize = m_messageBuffer.size ();
353350 m_messageBuffer.resize (currentSize + bytesReceived);
351+
354352 auto dataWritePos = m_messageBuffer.data () + currentSize;
355353 std::copy (m_receiveBuffer.data (), m_receiveBuffer.data () + bytesReceived, dataWritePos);
356354
@@ -394,8 +392,16 @@ void TcpConnection::ReadComplete(const boost_sys::error_code& error, size_t byte
394392 else if (std::numeric_limits<size_t >::max () == numBytes)
395393 {
396394 // We have a problem.
395+ numBytes = m_settings.minAmountToRead ;
397396 clearMsgBuf = true ;
398397 }
398+ else
399+ {
400+ // We do not want to ever reallocate the m_receiveBuffer beyond its initial
401+ // size, as this would cause a significant performance hit. We will always
402+ // read in up to DEFAULT_SMALL_RESERVED_SIZE chunks.
403+ numBytes = std::min (numBytes, static_cast <size_t >(DEFAULT_SMALL_RESERVED_SIZE ));
404+ }
399405 }
400406 catch (...)
401407 {
@@ -411,7 +417,16 @@ void TcpConnection::ReadComplete(const boost_sys::error_code& error, size_t byte
411417
412418 if (clearMsgBuf)
413419 {
414- m_messageBuffer.clear ();
420+ if (m_messageBuffer.capacity () > DEFAULT_LARGE_RESERVED_SIZE )
421+ {
422+ defs::char_buffer_t tmp;
423+ tmp.reserve (DEFAULT_LARGE_RESERVED_SIZE );
424+ m_messageBuffer.swap (tmp);
425+ }
426+ else
427+ {
428+ m_messageBuffer.clear ();
429+ }
415430 }
416431
417432 if (numBytes > 0 )
0 commit comments