Skip to content

Commit aab7ef6

Browse files
Anton KirilovNateBrady23
authored andcommitted
H2O: Avoid some memory allocations and copies (#2710)
1 parent 30e27d7 commit aab7ef6

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

frameworks/C/h2o/src/request_handler.c

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,14 @@ static int json_serializer(struct st_h2o_handler_t *self, h2o_req_t *req)
6565
static int plaintext(struct st_h2o_handler_t *self, h2o_req_t *req)
6666
{
6767
IGNORE_FUNCTION_PARAMETER(self);
68+
69+
h2o_generator_t generator;
70+
h2o_iovec_t body = {.base = HELLO_RESPONSE, .len = sizeof(HELLO_RESPONSE) - 1};
71+
72+
memset(&generator, 0, sizeof(generator));
6873
set_default_response_param(PLAIN, sizeof(HELLO_RESPONSE) - 1, req);
69-
h2o_send_inline(req, H2O_STRLIT(HELLO_RESPONSE));
74+
h2o_start_response(req, &generator);
75+
h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL);
7076
return 0;
7177
}
7278

@@ -179,21 +185,21 @@ int send_json_response(yajl_gen gen, bool free_gen, h2o_req_t *req)
179185
int ret = EXIT_FAILURE;
180186

181187
if (yajl_gen_get_buf(gen, &buf, &len) == yajl_gen_status_ok) {
188+
set_default_response_param(JSON, len, req);
189+
ret = EXIT_SUCCESS;
190+
182191
if (free_gen) {
183-
char * const body = h2o_mem_alloc_pool(&req->pool, len);
184-
185-
if (body) {
186-
memcpy(body, buf, len);
187-
yajl_gen_free(gen);
188-
set_default_response_param(JSON, len, req);
189-
h2o_send_inline(req, body, len);
190-
ret = EXIT_SUCCESS;
191-
}
192+
// h2o_send_inline() makes a copy of its input.
193+
h2o_send_inline(req, (char *) buf, len);
194+
yajl_gen_free(gen);
192195
}
193196
else {
194-
set_default_response_param(JSON, len, req);
195-
h2o_send_inline(req, (char *) buf, len);
196-
ret = EXIT_SUCCESS;
197+
h2o_generator_t generator;
198+
h2o_iovec_t body = {.base = (char *) buf, .len = len};
199+
200+
memset(&generator, 0, sizeof(generator));
201+
h2o_start_response(req, &generator);
202+
h2o_send(req, &body, 1, H2O_SEND_STATE_FINAL);
197203
}
198204
}
199205

0 commit comments

Comments
 (0)