Skip to content

Commit 516da48

Browse files
Reduce memory usage when generating patch output.
Instead of calling `rb_str_cat`, which will cause memory reallocations, we can build an array buffer first and join it.
1 parent 1405f96 commit 516da48

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

ext/rugged/rugged_patch.c

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,7 @@ static VALUE rb_git_diff_patch_lines(int argc, VALUE *argv, VALUE self)
275275

276276
return INT2FIX(lines);
277277
}
278+
278279
/*
279280
* call-seq:
280281
* patch.bytesize(options = {}) -> int
@@ -332,16 +333,16 @@ static int patch_print_cb(
332333
const git_diff_line *line,
333334
void *payload)
334335
{
335-
VALUE rb_str = (VALUE)payload;
336+
VALUE rb_buffer = (VALUE)payload;
336337

337338
switch (line->origin) {
338339
case GIT_DIFF_LINE_CONTEXT:
339340
case GIT_DIFF_LINE_ADDITION:
340341
case GIT_DIFF_LINE_DELETION:
341-
rb_str_cat(rb_str, &line->origin, 1);
342+
rb_ary_push(rb_buffer, rb_str_new(&line->origin, 1));
342343
}
343344

344-
rb_str_cat(rb_str, line->content, line->content_len);
345+
rb_ary_push(rb_buffer, rb_str_new(line->content, line->content_len));
345346

346347
return GIT_OK;
347348
}
@@ -352,16 +353,15 @@ static int patch_print_header_cb(
352353
const git_diff_line *line,
353354
void *payload)
354355
{
355-
VALUE rb_str = (VALUE)payload;
356+
VALUE rb_buffer = (VALUE)payload;
356357

357358
if (line->origin == GIT_DIFF_LINE_FILE_HDR) {
358-
rb_str_cat(rb_str, line->content, line->content_len);
359+
rb_ary_push(rb_buffer, rb_str_new(line->content, line->content_len));
359360
}
360361

361362
return GIT_OK;
362363
}
363364

364-
365365
/*
366366
* call-seq:
367367
* patch.to_s -> str
@@ -371,12 +371,12 @@ static int patch_print_header_cb(
371371
static VALUE rb_git_diff_patch_to_s(VALUE self)
372372
{
373373
git_patch *patch;
374-
VALUE rb_str = rb_str_new(NULL, 0);
374+
VALUE rb_buffer = rb_ary_new();
375375
Data_Get_Struct(self, git_patch, patch);
376376

377-
rugged_exception_check(git_patch_print(patch, patch_print_cb, (void*)rb_str));
377+
rugged_exception_check(git_patch_print(patch, patch_print_cb, (void*)rb_buffer));
378378

379-
return rb_str;
379+
return rb_ary_join(rb_buffer, Qnil);
380380
}
381381

382382
/*
@@ -388,12 +388,12 @@ static VALUE rb_git_diff_patch_to_s(VALUE self)
388388
static VALUE rb_git_diff_patch_header(VALUE self)
389389
{
390390
git_patch *patch;
391-
VALUE rb_str = rb_str_new(NULL, 0);
391+
VALUE rb_buffer = rb_ary_new();
392392
Data_Get_Struct(self, git_patch, patch);
393393

394-
rugged_exception_check(git_patch_print(patch, patch_print_header_cb, (void*)rb_str));
394+
rugged_exception_check(git_patch_print(patch, patch_print_header_cb, (void*)rb_buffer));
395395

396-
return rb_str;
396+
return rb_ary_join(rb_buffer, Qnil);
397397
}
398398

399399

0 commit comments

Comments
 (0)