Skip to content

Commit

Permalink
Reduce allocation on string multiplication
Browse files Browse the repository at this point in the history
  • Loading branch information
itchyny authored and wtlangford committed May 26, 2020
1 parent 9163e09 commit 6306ac8
Showing 1 changed file with 9 additions and 11 deletions.
20 changes: 9 additions & 11 deletions src/builtin.c
Original file line number Diff line number Diff line change
Expand Up @@ -320,19 +320,17 @@ static jv f_multiply(jq_state *jq, jv input, jv a, jv b) {
str = b;
num = a;
}
int n;
size_t alen = jv_string_length_bytes(jv_copy(str));
jv res = jv_copy(str);

for (n = jv_number_value(num) - 1; n > 0; n--)
res = jv_string_append_buf(res, jv_string_value(str), alen);

jv res = jv_null();
int n = jv_number_value(num);
if (n > 0) {
size_t alen = jv_string_length_bytes(jv_copy(str));
res = jv_string_empty(alen * n);
for (; n > 0; n--) {
res = jv_string_append_buf(res, jv_string_value(str), alen);
}
}
jv_free(str);
jv_free(num);
if (n < 0) {
jv_free(res);
return jv_null();
}
return res;
} else if (ak == JV_KIND_OBJECT && bk == JV_KIND_OBJECT) {
return jv_object_merge_recursive(a, b);
Expand Down

0 comments on commit 6306ac8

Please sign in to comment.