Skip to content
This repository has been archived by the owner on Oct 15, 2020. It is now read-only.

Commit

Permalink
chakrashim: Avoid calling JsCopyString twice to find length
Browse files Browse the repository at this point in the history
To find Utf8Length, we call `JsCopyString()` to find the length
of utf8 string and then another call to actually perform the copy
into the buffer. 2nd call is not needed for just finding length.

Gives approx. 2% win in acme-air on my machine.
  • Loading branch information
kunalspathak committed Jul 25, 2017
1 parent 92eb561 commit 43125ad
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 12 deletions.
28 changes: 18 additions & 10 deletions deps/chakrashim/src/jsrtutils.cc
Original file line number Diff line number Diff line change
Expand Up @@ -976,26 +976,34 @@ StringUtf8::~StringUtf8() {
}
}

JsErrorCode StringUtf8::LengthFrom(JsValueRef strRef) {
CHAKRA_ASSERT(_length == 0);

size_t len = 0;
IfJsErrorRet(JsCopyString(strRef, nullptr, 0, &len));

_length = len;
return JsNoError;
}

JsErrorCode StringUtf8::From(JsValueRef strRef) {
CHAKRA_ASSERT(!_str);

size_t len = 0;
IfJsErrorRet(JsCopyString(strRef, nullptr, 0, &len));
IfJsErrorRet(LengthFrom(strRef));
size_t len = length();

char* buffer = reinterpret_cast<char*>(malloc(len+1));
CHAKRA_VERIFY(buffer != nullptr);

size_t written = 0;
JsErrorCode errorCode = JsCopyString(strRef, buffer, len, &written);
IfJsErrorRet(JsCopyString(strRef, buffer, len, &written));

if (errorCode == JsNoError) {
CHAKRA_ASSERT(len == written);
buffer[len] = '\0';
_str = buffer;
_length = static_cast<int>(len);
}
CHAKRA_ASSERT(len == written);
buffer[len] = '\0';
_str = buffer;
_length = static_cast<int>(len);

return errorCode;
return JsNoError;
}

} // namespace jsrt
3 changes: 3 additions & 0 deletions deps/chakrashim/src/jsrtutils.h
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ class StringUtf8 {
operator const char *() const { return _str; }
int length() const { return static_cast<int>(_length); }
JsErrorCode From(JsValueRef strRef);
// This just initializes length field. _str will remain uninitialized.
// Use `From()` to initialize _str and _length
JsErrorCode LengthFrom(JsValueRef strRef);

private:
// Disallow copying and assigning
Expand Down
3 changes: 1 addition & 2 deletions deps/chakrashim/src/v8string.cc
Original file line number Diff line number Diff line change
Expand Up @@ -79,11 +79,10 @@ int String::Length() const {

int String::Utf8Length() const {
jsrt::StringUtf8 str;
if (str.From((JsValueRef)this) != JsNoError) {
if (str.LengthFrom((JsValueRef)this) != JsNoError) {
// error
return 0;
}

return str.length();
}

Expand Down

0 comments on commit 43125ad

Please sign in to comment.