Avoid re-allocating headers array in http_response

Allocate the headers array once with the default number of entries
sufficient for most requests, and only re-allocate if needed instead of
re-allocating with each header.
master
Jessie Murray 3 years ago
parent c7c6fc010f
commit dc9d1b646e
No known key found for this signature in database
GPG Key ID: E7E4D57EDDA744C5

@ -11,6 +11,14 @@
/* HTTP Response */ /* HTTP Response */
#define DEFAULT_HEADERS_ARRAY_SIZE 9
static void
http_response_allocate_headers(struct http_response *r) {
r->headers_array_size = DEFAULT_HEADERS_ARRAY_SIZE;
r->headers = calloc(r->headers_array_size, sizeof(struct http_header));
}
struct http_response * struct http_response *
http_response_init(struct worker *w, int code, const char *msg) { http_response_init(struct worker *w, int code, const char *msg) {
@ -26,6 +34,14 @@ http_response_init(struct worker *w, int code, const char *msg) {
r->w = w; r->w = w;
r->keep_alive = 0; /* default */ r->keep_alive = 0; /* default */
/* pre-allocate array for headers */
http_response_allocate_headers(r);
if(!r->headers) {
if(w && w->s) slog(w->s, WEBDIS_ERROR, "Failed to allocate http_response headers", 0);
free(r);
return NULL;
}
http_response_set_header(r, "Server", "Webdis", HEADER_COPY_NONE); http_response_set_header(r, "Server", "Webdis", HEADER_COPY_NONE);
/* Cross-Origin Resource Sharing, CORS. */ /* Cross-Origin Resource Sharing, CORS. */
@ -57,6 +73,14 @@ http_response_init_with_buffer(struct worker *w, char *data, size_t data_sz, int
} }
r->w = w; r->w = w;
/* pre-allocate array for headers */
http_response_allocate_headers(r);
if(!r->headers) {
if(w && w->s) slog(w->s, WEBDIS_ERROR, "Failed to allocate http_response headers", 0);
free(r);
return NULL;
}
/* provide buffer directly */ /* provide buffer directly */
r->out = data; r->out = data;
r->out_sz = data_sz; r->out_sz = data_sz;
@ -84,11 +108,13 @@ http_response_set_header(struct http_response *r, const char *k, const char *v,
} }
/* extend array */ /* extend array */
if(pos == r->header_count) { if(pos == r->headers_array_size) {
/* FIXME: allocation could fail */
r->headers = realloc(r->headers, r->headers = realloc(r->headers,
sizeof(struct http_header)*(r->header_count + 1)); sizeof(struct http_header)*(r->headers_array_size + 1));
r->header_count++; r->headers_array_size++;
} }
r->header_count++;
/* copy key if needed */ /* copy key if needed */
if(copy == HEADER_COPY_KEY) { if(copy == HEADER_COPY_KEY) {

@ -32,7 +32,8 @@ struct http_response {
const char *msg; const char *msg;
struct http_header *headers; struct http_header *headers;
int header_count; int header_count; /* actual count in array */
int headers_array_size; /* allocated size */
const char *body; const char *body;
size_t body_len; size_t body_len;

Loading…
Cancel
Save