Browse Source

src: speed up module loading, don't resize buffer

Don't bother shrinking the read buffer on the final read because we
dispose it immediately afterwards.  Avoids some unnecessary memory
allocation and copying.

PR-URL: https://github.com/nodejs/node/pull/9132
Reviewed-By: James M Snell <jasnell@gmail.com>
v6
Ben Noordhuis 8 years ago
parent
commit
d52f5dc864
  1. 18
      src/node_file.cc

18
src/node_file.cc

@ -546,10 +546,11 @@ static void InternalModuleReadFile(const FunctionCallbackInfo<Value>& args) {
return; return;
} }
const size_t kBlockSize = 32 << 10;
std::vector<char> chars; std::vector<char> chars;
int64_t offset = 0; int64_t offset = 0;
for (;;) { ssize_t numchars;
const size_t kBlockSize = 32 << 10; do {
const size_t start = chars.size(); const size_t start = chars.size();
chars.resize(start + kBlockSize); chars.resize(start + kBlockSize);
@ -558,24 +559,19 @@ static void InternalModuleReadFile(const FunctionCallbackInfo<Value>& args) {
buf.len = kBlockSize; buf.len = kBlockSize;
uv_fs_t read_req; uv_fs_t read_req;
const ssize_t numchars = numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
uv_fs_req_cleanup(&read_req); uv_fs_req_cleanup(&read_req);
CHECK_GE(numchars, 0); CHECK_GE(numchars, 0);
if (static_cast<size_t>(numchars) < kBlockSize) {
chars.resize(start + numchars);
break;
}
offset += numchars; offset += numchars;
} } while (static_cast<size_t>(numchars) == kBlockSize);
uv_fs_t close_req; uv_fs_t close_req;
CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr)); CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr));
uv_fs_req_cleanup(&close_req); uv_fs_req_cleanup(&close_req);
size_t start = 0; size_t start = 0;
if (chars.size() >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) { if (offset >= 3 && 0 == memcmp(&chars[0], "\xEF\xBB\xBF", 3)) {
start = 3; // Skip UTF-8 BOM. start = 3; // Skip UTF-8 BOM.
} }
@ -583,7 +579,7 @@ static void InternalModuleReadFile(const FunctionCallbackInfo<Value>& args) {
String::NewFromUtf8(env->isolate(), String::NewFromUtf8(env->isolate(),
&chars[start], &chars[start],
String::kNormalString, String::kNormalString,
chars.size() - start); offset - start);
args.GetReturnValue().Set(chars_string); args.GetReturnValue().Set(chars_string);
} }

Loading…
Cancel
Save