Skip to content

Commit 7438ab9

Browse files
mgcreaautofix-ci[bot]yusukebe
authored
perf(context): add fast path to c.json() matching c.text() optimization (#4707)
* perf: add fast path to c.json() matching c.text() optimization Skip #newResponse() and Headers allocation when no status, headers, or finalized state exists. Creates Response directly with inline Content-Type header, matching the existing c.text() fast path pattern. * ci: apply automated fixes * use `Response.json()` * don't use `any` * refactor with `useFastPath` --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: Yusuke Wada <yusuke@kamawada.com>
1 parent 034223f commit 7438ab9

1 file changed

Lines changed: 14 additions & 6 deletions

File tree

src/context.ts

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,10 @@ export class Context<
657657
headers?: HeaderRecord
658658
): ReturnType<BodyRespond> => this.#newResponse(data, arg, headers) as ReturnType<BodyRespond>
659659

660+
#useFastPath(): boolean {
661+
return !this.#preparedHeaders && !this.#status && !this.finalized
662+
}
663+
660664
/**
661665
* `.text()` can render text as `Content-Type:text/plain`.
662666
*
@@ -674,7 +678,7 @@ export class Context<
674678
arg?: ContentfulStatusCode | ResponseOrInit,
675679
headers?: HeaderRecord
676680
): ReturnType<TextRespond> => {
677-
return !this.#preparedHeaders && !this.#status && !arg && !headers && !this.finalized
681+
return this.#useFastPath() && !arg && !headers
678682
? (new Response(text) as ReturnType<TextRespond>)
679683
: (this.#newResponse(
680684
text,
@@ -703,11 +707,15 @@ export class Context<
703707
arg?: U | ResponseOrInit<U>,
704708
headers?: HeaderRecord
705709
): JSONRespondReturn<T, U> => {
706-
return this.#newResponse(
707-
JSON.stringify(object),
708-
arg,
709-
setDefaultContentType('application/json', headers)
710-
) /* eslint-disable @typescript-eslint/no-explicit-any */ as any
710+
return (
711+
this.#useFastPath() && !arg && !headers
712+
? Response.json(object)
713+
: this.#newResponse(
714+
JSON.stringify(object),
715+
arg,
716+
setDefaultContentType('application/json', headers)
717+
)
718+
) as JSONRespondReturn<T, U>
711719
}
712720

713721
html: HTMLRespond = (

0 commit comments

Comments
 (0)