Skip to content

Commit 0b5a010

Browse files
committed
perf: avoid memcpy when possible
1 parent 8dc8e48 commit 0b5a010

File tree

2 files changed

+25
-90
lines changed

2 files changed

+25
-90
lines changed

.vscode/settings.json

Lines changed: 0 additions & 83 deletions
This file was deleted.

binding.cc

Lines changed: 25 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,29 @@ static bool IsObject (napi_env env, napi_value value) {
9595
return type == napi_object;
9696
}
9797

98+
std::string toString(napi_env& env, const napi_value& from) {
99+
size_t size = 0;
100+
if (IsString(env, from)) {
101+
napi_get_value_string_utf8(env, from, NULL, 0, &size); // TODO(fix): assert(napi_ok)
102+
// TODO (perf): How to avoid extra copy?
103+
if (size < 4096) {
104+
char store[4096];
105+
napi_get_value_string_utf8(env, from, store, 4096, &size); // TODO(fix): assert(napi_ok)
106+
return std::string(store, size);
107+
} else {
108+
std::unique_ptr<char[]> store(new char[size + 1]);
109+
napi_get_value_string_utf8(env, from, store.get(), size + 1, &size); // TODO(fix): assert(napi_ok)
110+
return std::string(store.get(), size);
111+
}
112+
} else if (IsBuffer(env, from)) {
113+
char* data = nullptr;
114+
napi_get_buffer_info(env, from, reinterpret_cast<void**>(&data), &size); // TODO(fix): assert(napi_ok)
115+
return std::string(data, size);
116+
}
117+
118+
return "";
119+
}
120+
98121
/**
99122
* Create an error object.
100123
*/
@@ -259,10 +282,7 @@ static std::optional<std::string> RangeOption (napi_env env, napi_value opts, co
259282
napi_value value = GetProperty(env, opts, name);
260283

261284
if (StringOrBufferLength(env, value) >= 0) {
262-
LD_STRING_OR_BUFFER_TO_COPY(env, value, to);
263-
auto str = std::string(toCh_, toSz_);
264-
delete[] toCh_;
265-
return str;
285+
return toString(env, value);
266286
}
267287
}
268288

@@ -284,9 +304,7 @@ static std::vector<std::string>* KeyArray (napi_env env, napi_value arr) {
284304

285305
if (napi_get_element(env, arr, i, &element) == napi_ok &&
286306
StringOrBufferLength(env, element) >= 0) {
287-
LD_STRING_OR_BUFFER_TO_COPY(env, element, to);
288-
result->emplace_back(toCh_, toSz_);
289-
delete [] toCh_;
307+
result->push_back(toString(env, element));
290308
}
291309
}
292310
}

0 commit comments

Comments
 (0)