Skip to content

Commit e17e6fb

Browse files
committed
util: use on-stack buffer for Utf8Value
Improves `crypto.createHash().update().digest()` performance by 10%. PR-URL: #670 Reviewed-By: Ben Noordhuis <[email protected]>
1 parent 3d4e96f commit e17e6fb

File tree

2 files changed

+11
-3
lines changed

2 files changed

+11
-3
lines changed

src/util.cc

+7-2
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,20 @@ Utf8Value::Utf8Value(v8::Isolate* isolate, v8::Handle<v8::Value> value)
1616
// Allocate enough space to include the null terminator
1717
size_t len = StringBytes::StorageSize(val_, UTF8) + 1;
1818

19-
char* str = static_cast<char*>(calloc(1, len));
19+
char* str;
20+
if (len > kStorageSize)
21+
str = static_cast<char*>(malloc(len));
22+
else
23+
str = str_st_;
24+
CHECK_NE(str, NULL);
2025

2126
int flags = WRITE_UTF8_FLAGS;
22-
flags |= ~v8::String::NO_NULL_TERMINATION;
2327

2428
length_ = val_->WriteUtf8(str,
2529
len,
2630
0,
2731
flags);
32+
str[length_] = '\0';
2833

2934
str_ = reinterpret_cast<char*>(str);
3035
}

src/util.h

+4-1
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,8 @@ class Utf8Value {
110110
explicit Utf8Value(v8::Isolate* isolate, v8::Handle<v8::Value> value);
111111

112112
~Utf8Value() {
113-
free(str_);
113+
if (str_ != str_st_)
114+
free(str_);
114115
}
115116

116117
char* operator*() {
@@ -126,7 +127,9 @@ class Utf8Value {
126127
};
127128

128129
private:
130+
static const int kStorageSize = 1024;
129131
size_t length_;
132+
char str_st_[kStorageSize];
130133
char* str_;
131134
};
132135

0 commit comments

Comments
 (0)