diff --git a/lib/src/HttpAppFrameworkImpl.cc b/lib/src/HttpAppFrameworkImpl.cc index 53f1789a..0951ca0e 100644 --- a/lib/src/HttpAppFrameworkImpl.cc +++ b/lib/src/HttpAppFrameworkImpl.cc @@ -534,9 +534,16 @@ void HttpAppFrameworkImpl::run() #endif // Create all listeners. auto ioLoops = listenerManagerPtr_->createListeners( - std::bind(&HttpAppFrameworkImpl::onAsyncRequest, this, _1, _2), - std::bind(&HttpAppFrameworkImpl::onNewWebsockRequest, this, _1, _2, _3), - std::bind(&HttpAppFrameworkImpl::onConnection, this, _1), + [this](const HttpRequestImplPtr &req, + std::function &&callback) { + onAsyncRequest(req, std::move(callback)); + }, + [this](const HttpRequestImplPtr &req, + std::function &&callback, + const WebSocketConnectionImplPtr &wsConnPtr) { + onNewWebsockRequest(req, std::move(callback), wsConnPtr); + }, + [this](const trantor::TcpConnectionPtr &conn) { onConnection(conn); }, idleConnectionTimeout_, sslCertPath_, sslKeyPath_, diff --git a/lib/src/HttpServer.cc b/lib/src/HttpServer.cc index 2e02b893..e1e152bb 100644 --- a/lib/src/HttpServer.cc +++ b/lib/src/HttpServer.cc @@ -299,6 +299,34 @@ void HttpServer::onMessage(const TcpConnectionPtr &conn, MsgBuffer *buf) } } +struct CallBackParamPack +{ + CallBackParamPack() = default; + CallBackParamPack(const trantor::TcpConnectionPtr &conn_, + const HttpRequestImplPtr &req_, + const std::shared_ptr &loopFlag_, + const std::shared_ptr &requestParser_, + bool *syncFlagPtr_, + bool close_, + bool isHeadMethod_) + : conn(conn_), + req(req_), + loopFlag(loopFlag_), + requestParser(requestParser_), + syncFlagPtr(syncFlagPtr_), + close(close_), + isHeadMethod(isHeadMethod_) + { + } + trantor::TcpConnectionPtr conn; + HttpRequestImplPtr req; + std::shared_ptr loopFlag; + std::shared_ptr requestParser; + bool *syncFlagPtr; + bool close; + bool isHeadMethod; +}; + void HttpServer::onRequests( const TcpConnectionPtr &conn, const std::vector &requests, @@ -373,16 +401,28 @@ void HttpServer::onRequests( if (adviceFlag) continue; } + + // Optimization: Avoids dynamic allocation when copying the callback in + // handlers (ex: copying callback into lambda captures in DB calls) + auto paramPack = std::make_shared(conn, + req, + loopFlagPtr, + requestParser, + &syncFlag, + close_, + isHeadMethod); httpAsyncCallback_( req, - [conn, - close_, - req, - loopFlagPtr, - &syncFlag, - isHeadMethod, - this, - requestParser](const HttpResponsePtr &response) { + [paramPack = std::move(paramPack), + this](const HttpResponsePtr &response) { + auto &conn = paramPack->conn; + auto &close_ = paramPack->close; + auto &req = paramPack->req; + auto &syncFlag = *paramPack->syncFlagPtr; + auto &isHeadMethod = paramPack->isHeadMethod; + auto &loopFlagPtr = paramPack->loopFlag; + auto &requestParser = paramPack->requestParser; + if (!response) return; if (!conn->connected())