Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Performance: reserve body to avoid frequent reallocations and copies #1788

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions httplib.h
Original file line number Diff line number Diff line change
Expand Up @@ -7461,6 +7461,21 @@ inline bool ClientImpl::process_request(Stream &strm, Request &req,
error = Error::Read;
return false;
}

// If we know the content length, reserve the expected size in the output
// buffer to avoid re-allocations and copies when appending received data
auto it = res.headers.find("Content-Length");
if (it != res.headers.end()) {
try {
int content_length = std::stoi(it->second);
// Check for unexpected values
if (content_length > 0 && content_length < 256*1024*1024 /* 256 MB */) {
res.body.reserve(content_length);
}
} catch(...) {
// Conversion error: ignore it. We will act like if no Content-Length header was provided
}
}

// Body
if ((res.status != StatusCode::NoContent_204) && req.method != "HEAD" &&
Expand Down