Skip to content

Commit

Permalink
util: use on-stack buffer for Utf8Value
Browse files Browse the repository at this point in the history
Improves `crypto.createHash().update().digest()` performance by 10%.

PR-URL: #670
Reviewed-By: Ben Noordhuis <[email protected]>
  • Loading branch information
indutny committed Jan 30, 2015
1 parent 3d4e96f commit e17e6fb
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
9 changes: 7 additions & 2 deletions src/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,20 @@ Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Handle<v8::Value> value)
// Allocate enough space to include the null terminator
size_t len = StringBytes::StorageSize(val_, UTF8) + 1;

char* str = static_cast<char*>(calloc(1, len));
char* str;
if (len > kStorageSize)
str = static_cast<char*>(malloc(len));
else
str = str_st_;
CHECK_NE(str, NULL);

int flags = WRITE_UTF8_FLAGS;
flags |= ~v8::String::NO_NULL_TERMINATION;

length_ = val_->WriteUtf8(str,
len,
0,
flags);
str[length_] = '\0';

str_ = reinterpret_cast<char*>(str);
}
Expand Down
5 changes: 4 additions & 1 deletion src/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ class Utf8Value {
explicit Utf8Value(v8::Isolate* isolate, v8::Handle<v8::Value> value);

~Utf8Value() {
free(str_);
if (str_ != str_st_)
free(str_);
}

char* operator*() {
Expand All @@ -126,7 +127,9 @@ class Utf8Value {
};

private:
static const int kStorageSize = 1024;
size_t length_;
char str_st_[kStorageSize];
char* str_;
};

Expand Down

0 comments on commit e17e6fb

Please sign in to comment.