libcpr / cpr

C++ Requests: Curl for People, a spiritual port of Python Requests.
https://docs.libcpr.org/
Other
6.29k stars 903 forks source link

parseHeader optimization: no intermediate std::vector #1062

Closed dayjaby closed 2 weeks ago

dayjaby commented 3 weeks ago

The header is parsed line by line. However, it's not necessary to store the lines in an intermediate std::vector before doing the parsing. As by doing so, we used 2 heap allocations per header line, which are optimized away by this PR.

Test example:

#include <memory>
#include <string>

#include "cpr/cpr.h"
#include "cpr/cprtypes.h"
#include "cpr/redirect.h"
#include "cpr/session.h"
#include "httpServer.hpp"

using namespace cpr;

int main() {
    HttpServer server;
    server.SetUp();
    std::cout << server.GetBaseUrl() << std::endl;
    Url url{server.GetBaseUrl() + "/hello.html"};
    Response response = cpr::Get(url);
    std::cout << response.header["content-type"];
    server.TearDown();
    return 0;
}

Before, measured with valgrind ./main:

==207737==   total heap usage: 138 allocs, 138 frees, 115,676 bytes allocated

With this PR:

==251897==   total heap usage: 132 allocs, 132 frees, 115,390 bytes allocated