You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Request to improve performance of stringifying in internal codes #2498
The cpp binding function, utf8slice called by Buffer.toString() is accounted for a big proportion in the CPU profile resulted from benchmarking a HTTP proxy using undici.
By using Uint8Arrray, we can eliminat the overhead incurred by the language transition
Reproducible By
constdispatcher=newPool('http://127.0.0.1:8090'/* an 4worker nginx */,{pipelining: 30,connections: 100,});constproxy=http.createServer((req,res)=>{dispatcher.request({// the constructor of RequestHandler in undici/lib/api/api-request.jsmethod: req.method,path: req.url,headers: req.headers,body: req,},(err,{ statusCode, headers, body /** a Readable */})=>{if(err){throwerr}res.writeHead(statusCode,headers);pipe(body,res);});});functionpipe(src,dst){src.on('readable',()=>{letchunk;while(null!==(chunk=src.read(65536))){dst.write(chunk);}});src.on('end',()=>{dst.end()});}
Expected Behavior
Logs & Screenshots
Environment
node v22
linux
Additional context
I hope the members can provide some guide and more importantly caveats to applying this idea
changed the title [-]Request to replace FastBuffer with Uint8Arrray in internal codes for performance[/-][+]Request to improve performance of stringifying in internal codes[/+]on Dec 5, 2023
One caveat I found nodejs/node#17431. %TypedArray%.prototype.subarray suffers from an upstream bug and plays slow. However, I think %TypedArray%.prototype.toString will be faster than Buffer.prototype.toString, thanks to the saved language switch
When is utf8Slice called? And what faster option does Uint8Array provide?
Sorry for the careless reply. The original motivation of this issue is that since the binding function, utf8Slice becomes the second largest contributor to CPU among all functions in HTTP module, I think we should works on a more efficent alternative, probably a pure js one.
Yes, Uint8Array.toString is not we want, TextDecoder is one thing I comes up with, but my benchmark shows it does not have advantage, which is out of my expectation
You are taking small buffers and converting them into v8 strings. It is highly likely that the bottleneck is in the speed of creating v8 strings from an array of bytes.
We can do some profiling to verify...
Regarding toString() (first half of the benchmark), the time spent is as follows (Node 20):
I think the point here is that we might not have to create the strings. We could e.g hash the buffer and re use strings. Or some other way to lookup common header names from buffer to string.
Activity
ronag commentedon Dec 5, 2023
FastBufferis pretty much anUint8Arrraywith some helper methods. How exactly would it make it faster?ywave620 commentedon Dec 5, 2023
At least, no language switch overhead from these

[-]Request to replace FastBuffer with Uint8Arrray in internal codes for performance[/-][+]Request to improve performance of stringifying in internal codes[/+]ywave620 commentedon Dec 5, 2023
One caveat I found nodejs/node#17431. %TypedArray%.prototype.subarray suffers from an upstream bug and plays slow. However, I think %TypedArray%.prototype.toString will be faster than Buffer.prototype.toString, thanks to the saved language switch
ronag commentedon Dec 5, 2023
When is utf8Slice called? And what faster option does Uint8Array provide?
ronag commentedon Dec 5, 2023
Do you have a benchmark?
ronag commentedon Dec 5, 2023
I think this should be fixed in Node if it's faster.
ronag commentedon Dec 5, 2023
Uint8Array.toStringandBuffer.toStringdon't do the same thing...ywave620 commentedon Dec 5, 2023
Sorry for the careless reply. The original motivation of this issue is that since the binding function, utf8Slice becomes
the second largest contributorto CPU among all functions in HTTP module, I think we should works on a more efficent alternative, probably a pure js one.Yes,
Uint8Array.toStringis not we want, TextDecoder is one thing I comes up with, but my benchmark shows it does not have advantage, which is out of my expectationywave620 commentedon Dec 5, 2023
So if Buffer.toString is slow and has no room to improve, can we skip it as possible as we can.
Maybe in
undici/lib/core/util.js
Line 227 in e218fc6
If
headers[i]represents a known header field, we can use the cached string rather than calltoStringon it to get one.ronag commentedon Dec 5, 2023
The question is how to achieve that... you would need to somehow determine that a specific buffer corresponds to a specific string.
ronag commentedon Dec 5, 2023
@anonrig
ronag commentedon Dec 5, 2023
We have to constraints in our favor:
ronag commentedon Dec 5, 2023
@lemire
lemire commentedon Dec 5, 2023
You are taking small buffers and converting them into v8 strings. It is highly likely that the bottleneck is in the speed of creating v8 strings from an array of bytes.
We can do some profiling to verify...
Regarding
toString()(first half of the benchmark), the time spent is as follows (Node 20):We can compare Bun with Node.
Node: default: 128.842ms
Bun: 58.57ms
So Bun is 2x faster.
Regarding the second half...
We can compare Bun with Node.
Node: default: 128.932ms
Bun: 58.88ms
So Bun is 2x faster, again.
So
DecodeUTF8is a bottleneck in both instances. Its code looks like this...The relevant part is this...
Local<Value> error; MaybeLocal<Value> maybe_ret = StringBytes::Encode(env->isolate(), data, length, UTF8, &error);It calls...
{ val = String::NewFromUtf8(isolate, buf, v8::NewStringType::kNormal, buflen); Local<String> str; if (!val.ToLocal(&str)) { *error = node::ERR_STRING_TOO_LONG(isolate); } return str; }... which calls....
which calls...
And down, down we go... turtles all the way down.
So yeah, it is likely a fairly expensive process.
And as long as you must create a v8 string, I don't see much in the way of possible optimization. It costs what it costs.
ronag commentedon Dec 5, 2023
I think the point here is that we might not have to create the strings. We could e.g hash the buffer and re use strings. Or some other way to lookup common header names from buffer to string.
lemire commentedon Dec 5, 2023
You can use the fact that UTF-8 validation can be done nearly for free in Node directly in a buffer thanks to @anonrig.
ronag commentedon Dec 6, 2023
Do we even need to utf validate header strings? Shouldn't they be ASCII? I think llhttp might already validate that?
ronag commentedon Dec 6, 2023
So I was thinking something like:
tsctx commentedon Dec 6, 2023
I think I could use a tree structure.
It is more efficient because there is no need to lowercase.
Benchmark
ronag commentedon Dec 6, 2023
What about
const key = buffer[i] & ~32;to lowercase?tsctx commentedon Dec 6, 2023
I can work on this, what do you want me to do?
ronag commentedon Dec 6, 2023
headerToString(don't assume ascii) andheaderToStringUnsafe(assume ascii).You tree lookup method seems like a good first try.
tsctx commentedon Dec 6, 2023
Let's go with that.
I think
allowUnsafeis better thanencoding.tsctx commentedon Dec 6, 2023
This is not necessary, because even if it is uppercase, it already has a lowercase reference.