Skip to content

Commit 3d4cecf

Browse files
committed
Reduce number of heap allocations for string array
1 parent 1a74a2d commit 3d4cecf

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

generate/templates/manual/src/str_array_converter.cc

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,17 @@ git_strarray *StrArrayConverter::Convert(Handle<v8::Value> val) {
2424
}
2525
}
2626

27+
static git_strarray * AllocGitStrArray(const size_t count) {
28+
const size_t size = sizeof(git_strarray) + (sizeof(char*) * count);
29+
uint8_t* memory = reinterpret_cast<uint8_t*>(malloc(size));
30+
git_strarray *result = reinterpret_cast<git_strarray *>(memory);
31+
result->count = count;
32+
result->strings = reinterpret_cast<char**>(memory + sizeof(git_strarray));
33+
return result;
34+
}
35+
2736
git_strarray *StrArrayConverter::ConvertArray(Array *val) {
28-
git_strarray *result = (git_strarray *)malloc(sizeof(git_strarray));
29-
result->count = val->Length();
30-
result->strings = (char **)malloc(sizeof(char*) * result->count);
37+
git_strarray *result = AllocGitStrArray(val->Length());
3138

3239
for(size_t i = 0; i < result->count; i++) {
3340
NanUtf8String entry(val->Get(i));
@@ -47,9 +54,7 @@ git_strarray* StrArrayConverter::ConvertString(Handle<String> val) {
4754
}
4855

4956
git_strarray *StrArrayConverter::ConstructStrArray(int argc, char** argv) {
50-
git_strarray *result = (git_strarray *)malloc(sizeof(git_strarray));
51-
result->count = argc;
52-
result->strings = (char **)malloc(sizeof(char*) * result->count);
57+
git_strarray *result = AllocGitStrArray(argc);
5358

5459
for(size_t i = 0; i < result->count; i++) {
5560
result->strings[i] = strdup(argv[i]);

0 commit comments

Comments
 (0)