Skip to content

Commit 0637fd9

Browse files
committed
perf: use one text encoder for fetch body
1 parent 5891e8f commit 0637fd9

1 file changed

Lines changed: 7 additions & 7 deletions

File tree

lib/fetch/body.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@ function extractBody (object, keepalive = false) {
2525
ReadableStream = require('stream/web').ReadableStream
2626
}
2727

28+
const textEncoder = new TextEncoder()
29+
2830
// 1. Let stream be null.
2931
let stream = null
3032

@@ -41,7 +43,7 @@ function extractBody (object, keepalive = false) {
4143
stream = new ReadableStream({
4244
async pull (controller) {
4345
controller.enqueue(
44-
typeof source === 'string' ? new TextEncoder().encode(source) : source
46+
typeof source === 'string' ? textEncoder.encode(source) : source
4547
)
4648
queueMicrotask(() => readableStreamClose(controller))
4749
},
@@ -108,17 +110,15 @@ function extractBody (object, keepalive = false) {
108110
// Set action to this step: run the multipart/form-data
109111
// encoding algorithm, with object’s entry list and UTF-8.
110112
action = async function * (object) {
111-
const enc = new TextEncoder()
112-
113113
for (const [name, value] of object) {
114114
if (typeof value === 'string') {
115-
yield enc.encode(
115+
yield textEncoder.encode(
116116
prefix +
117117
`; name="${escape(normalizeLinefeeds(name))}"` +
118118
`\r\n\r\n${normalizeLinefeeds(value)}\r\n`
119119
)
120120
} else {
121-
yield enc.encode(
121+
yield textEncoder.encode(
122122
prefix +
123123
`; name="${escape(normalizeLinefeeds(name))}"` +
124124
(value.name ? `; filename="${escape(value.name)}"` : '') +
@@ -130,11 +130,11 @@ function extractBody (object, keepalive = false) {
130130

131131
yield * value.stream()
132132

133-
yield enc.encode('\r\n')
133+
yield textEncoder.encode('\r\n')
134134
}
135135
}
136136

137-
yield enc.encode(`--${boundary}--`)
137+
yield textEncoder.encode(`--${boundary}--`)
138138
}
139139

140140
// Set source to object.

0 commit comments

Comments
 (0)