Skip to content

Commit

Permalink
src: speed up module loading, don't resize buffer
Browse files Browse the repository at this point in the history
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: #9132
Reviewed-By: James M Snell <jasnell@gmail.com>
  • Loading branch information
bnoordhuis authored and evanlucas committed Nov 2, 2016
1 parent 362c307 commit 8b53f3c
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions src/node_file.cc
Original file line number Diff line number Diff line change
Expand Up @@ -546,10 +546,11 @@ static void InternalModuleReadFile(const FunctionCallbackInfo<Value>& args) {
return;
}

const size_t kBlockSize = 32 << 10;
std::vector<char> chars;
int64_t offset = 0;
for (;;) {
const size_t kBlockSize = 32 << 10;
ssize_t numchars;
do {
const size_t start = chars.size();
chars.resize(start + kBlockSize);

Expand All @@ -558,32 +559,27 @@ static void InternalModuleReadFile(const FunctionCallbackInfo<Value>& args) {
buf.len = kBlockSize;

uv_fs_t read_req;
const ssize_t numchars =
uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
numchars = uv_fs_read(loop, &read_req, fd, &buf, 1, offset, nullptr);
uv_fs_req_cleanup(&read_req);

CHECK_GE(numchars, 0);
if (static_cast<size_t>(numchars) < kBlockSize) {
chars.resize(start + numchars);
break;
}
offset += numchars;
}
} while (static_cast<size_t>(numchars) == kBlockSize);

uv_fs_t close_req;
CHECK_EQ(0, uv_fs_close(loop, &close_req, fd, nullptr));
uv_fs_req_cleanup(&close_req);

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.
}

Local<String> chars_string =
String::NewFromUtf8(env->isolate(),
&chars[start],
String::kNormalString,
chars.size() - start);
offset - start);
args.GetReturnValue().Set(chars_string);
}

Expand Down

0 comments on commit 8b53f3c

Please sign in to comment.