Skip to content

Commit a340a25

Browse files
authored
perf(context): use createResponseInstance for new Response (#4733)
1 parent bd26c31 commit a340a25

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

src/context.ts

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,11 @@ const setDefaultContentType = (contentType: string, headers?: HeaderRecord): Hea
285285
}
286286
}
287287

288+
const createResponseInstance = (
289+
body?: BodyInit | null | undefined,
290+
init?: globalThis.ResponseInit
291+
): Response => new Response(body, init)
292+
288293
export class Context<
289294
// eslint-disable-next-line @typescript-eslint/no-explicit-any
290295
E extends Env = any,
@@ -396,7 +401,7 @@ export class Context<
396401
* The Response object for the current request.
397402
*/
398403
get res(): Response {
399-
return (this.#res ||= new Response(null, {
404+
return (this.#res ||= createResponseInstance(null, {
400405
headers: (this.#preparedHeaders ??= new Headers()),
401406
}))
402407
}
@@ -408,7 +413,7 @@ export class Context<
408413
*/
409414
set res(_res: Response | undefined) {
410415
if (this.#res && _res) {
411-
_res = new Response(_res.body, _res)
416+
_res = createResponseInstance(_res.body, _res)
412417
for (const [k, v] of this.#res.headers.entries()) {
413418
if (k === 'content-type') {
414419
continue
@@ -509,7 +514,7 @@ export class Context<
509514
*/
510515
header: SetHeaders = (name, value, options): void => {
511516
if (this.finalized) {
512-
this.#res = new Response((this.#res as Response).body, this.#res)
517+
this.#res = createResponseInstance((this.#res as Response).body, this.#res)
513518
}
514519
const headers = this.#res ? this.#res.headers : (this.#preparedHeaders ??= new Headers())
515520
if (value === undefined) {
@@ -630,7 +635,7 @@ export class Context<
630635
}
631636

632637
const status = typeof arg === 'number' ? arg : (arg?.status ?? this.#status)
633-
return new Response(data, { status, headers: responseHeaders })
638+
return createResponseInstance(data, { status, headers: responseHeaders })
634639
}
635640

636641
newResponse: NewResponse = (...args) => this.#newResponse(...(args as Parameters<NewResponse>))
@@ -684,7 +689,7 @@ export class Context<
684689
headers?: HeaderRecord
685690
): ReturnType<TextRespond> => {
686691
return this.#useFastPath() && !arg && !headers
687-
? (new Response(text) as ReturnType<TextRespond>)
692+
? (createResponseInstance(text) as ReturnType<TextRespond>)
688693
: (this.#newResponse(
689694
text,
690695
arg,
@@ -777,7 +782,7 @@ export class Context<
777782
* ```
778783
*/
779784
notFound = (): ReturnType<NotFoundHandler> => {
780-
this.#notFoundHandler ??= () => new Response()
785+
this.#notFoundHandler ??= () => createResponseInstance()
781786
return this.#notFoundHandler(this)
782787
}
783788
}

0 commit comments

Comments
 (0)