diff options
author | Brendan Ashworth <brendan.ashworth@me.com> | 2015-05-16 05:24:34 +0300 |
---|---|---|
committer | Brendan Ashworth <brendan.ashworth@me.com> | 2015-05-23 01:31:03 +0300 |
commit | 9da168b71fb729635ad71e839630480e815623d0 (patch) | |
tree | 0f508d18ed0180c410dbb62b77a15dc9ab919a71 /src | |
parent | 2a71f02988244b6299db8fe8ba3cc0491793acfc (diff) |
buffer: optimize Buffer.byteLength
Buffer.byteLength is important for speed because it is called whenever a
new Buffer is created from a string.
This commit optimizes Buffer.byteLength execution by:
- moving base64 length calculation into JS-land, which is now much
faster
- remove redundant code and streamline the UTF8 length calculation
It also adds a benchmark and better tests.
PR-URL: https://github.com/nodejs/io.js/pull/1713
Reviewed-By: Trevor Norris <trev.norris@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
Diffstat (limited to 'src')
-rw-r--r-- | src/node_buffer.cc | 16 |
1 files changed, 5 insertions, 11 deletions
diff --git a/src/node_buffer.cc b/src/node_buffer.cc index bd022792125..fca08599e50 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -541,17 +541,11 @@ void WriteDoubleBE(const FunctionCallbackInfo<Value>& args) { } -void ByteLength(const FunctionCallbackInfo<Value> &args) { - Environment* env = Environment::GetCurrent(args); - - if (!args[0]->IsString()) - return env->ThrowTypeError("Argument must be a string"); - - Local<String> s = args[0]->ToString(env->isolate()); - enum encoding e = ParseEncoding(env->isolate(), args[1], UTF8); +void ByteLengthUtf8(const FunctionCallbackInfo<Value> &args) { + CHECK(args[0]->IsString()); - uint32_t size = StringBytes::Size(env->isolate(), s, e); - args.GetReturnValue().Set(size); + // Fast case: avoid StringBytes on UTF8 string. Jump to v8. + args.GetReturnValue().Set(args[0].As<String>()->Utf8Length()); } @@ -745,7 +739,7 @@ void Initialize(Handle<Object> target, env->SetMethod(target, "setupBufferJS", SetupBufferJS); - env->SetMethod(target, "byteLength", ByteLength); + env->SetMethod(target, "byteLengthUtf8", ByteLengthUtf8); env->SetMethod(target, "compare", Compare); env->SetMethod(target, "fill", Fill); env->SetMethod(target, "indexOfBuffer", IndexOfBuffer); |