perf(jsx): JSX performance improvement (#444)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* perf(jsx): Update benchmark for JSX. * perf(utils/html): Improve `escape` performance. Improved `escape` performance with reference to the react-dom implementation. * refactor(utils/html): Subdivide HtmlEscapedString * perf(jsx): Rewrite JSX with new `escapeToBuffer` and `JSXNode`. * refactor(jsx): A function `jsx` returns `JSXNode` now. * perf(html): Rewrite html middleware with new `escapeToBuffer`. * Update tests for JSX. * Update tests for utils/html.
authored by Taku Amano · committed by GitHub · parent dab3c26 · Browse files · 7 files·+258 added−91 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+258 added−91 removed
- tests:+74 added−9 removed
- other:+184 added−82 removed
Provenance
- Commit
85cbf3e- Tree
cddbdd9- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
dab3c26
7 files changed+258 added−91 removed
modified:benchmarks/jsx/index.tsx+5 added-5 removed
23 unmodified lines24252627282930313228293031323334353636 unmodified lines23 unmodified lines )
const Form = () => ( <form> <input type='text' value='a' readonly tabindex={1} /> <input type='checkbox' value='b' checked={true} tabindex={2} /> <input type='checkbox' value='c' checked={true} tabindex={3} /> <input type='checkbox' value='d' checked={false} tabindex={4} /> <input type='checkbox' value='e' checked={false} tabindex={5} /> <input type='text' value='1234567890 < 1234567891' readonly tabindex={1} /> <input type='checkbox' value='1234567890 < 1234567891' checked={true} tabindex={2} /> <input type='checkbox' value='1234567890 < 1234567891' checked={true} tabindex={3} /> <input type='checkbox' value='1234567890 < 1234567891' checked={false} tabindex={4} /> <input type='checkbox' value='1234567890 < 1234567891' checked={false} tabindex={5} /> </form> )
return () => (36 unmodified linesmodified:src/middleware/html/index.ts+15 added-11 removed
112334456789101113121314161516171819202121222323242425262728292630313233303435323637import { escape } from '../../utils/html'import { escapeToBuffer } from '../../utils/html'import type { Buffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'
export type HtmlEscapedString = string & { isEscaped: true }
export const raw = (value: any): HtmlEscapedString => { const escapedString = new String(value) as HtmlEscapedString escapedString.isEscaped = true
return escapedString}
export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => { let result = '' const buffer: Buffer = ['']
for (let i = 0, len = strings.length - 1; i < len; i++) { result += strings[i] buffer[0] += strings[i]
const children = values[i] instanceof Array ? values[i].flat(Infinity) : [values[i]] for (let i = 0, len = children.length; i < len; i++) { const child = children[i] if (typeof child === 'string') { escapeToBuffer(child, buffer) if (typeof child === 'boolean' || child === null || child === undefined) { } else if (typeof child === 'boolean' || child === null || child === undefined) { continue } else if (typeof child === 'object' && (child as any).isEscaped) { result += child } else if ( (typeof child === 'object' && (child as HtmlEscaped).isEscaped) || typeof child === 'number' ) { buffer[0] += child } else { result += escape(child.toString()) escapeToBuffer(child.toString(), buffer) } } } result += strings[strings.length - 1] buffer[0] += strings[strings.length - 1]
return raw(result) return raw(buffer[0])}modified:src/middleware/jsx/index.test.tsx+54 added-4 removed
1 import { Hono } from '../../hono'2+import { html } from '../html/index'3 import { jsx, memo, Fragment } from './index'4 5+interface SiteData {6+ title: string7+ children?: any8+}9+10 describe('JSX middleware', () => {5- const app = new Hono()11+ let app: Hono12 13+ beforeEach(() => {14+ app = new Hono()15+ })16+17 it('Should render HTML strings', async () => {18 app.get('/', (c) => {19 return c.html(<h1>Hello</h1>)20 })1 unmodified line22 expect(res.status).toBe(200)23 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')24 expect(await res.text()).toBe('<h1>Hello</h1>')25 })26+27+ it('Should be able to be used with html middleware', async () => {28+ const Layout = (props: SiteData) => html`<!DOCTYPE html>29+ <html>30+ <head>31+ <title>${props.title}</title>32+ </head>33+ <body>34+ ${props.children}35+ </body>36+ </html>`37+38+ const Content = (props: { siteData: SiteData; name: string }) => (39+ <Layout {...props.siteData}>40+ <h1>{props.name}</h1>41+ </Layout>42+ )43+44+ app.get('/', (c) => {45+ const props = {46+ name: 'JSX',47+ siteData: {48+ title: 'with html middleware',49+ },50+ }51+ return c.html(<Content {...props} />)52+ })53+ const res = await app.request('http://localhost/')54+ expect(res.status).toBe(200)55+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')56+ expect(await res.text()).toBe(`<!DOCTYPE html>57+ <html>58+ <head>59+ <title>with html middleware</title>60+ </head>61+ <body>62+ <h1>JSX</h1>63+ </body>64+ </html>`)65+ })66 })67 68 describe('render to string', () => {69 it('Nested array', () => {28 unmodified lines98 expect(template.toString()).toBe('<span>" is allowed here</span>')99 })100 101 it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {52- expect(() => (53- <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>54- )).toThrow()102+ expect(() =>103+ (<span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>).toString()104+ ).toThrow()105 })106 })107 108 // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored236 unmodified linesmodified:src/middleware/jsx/index.ts+108 added-54 removed
1-import { escape } from '../../utils/html'2-import type { HtmlEscapedString } from '../../utils/html'1+import { escapeToBuffer } from '../../utils/html'2+import type { Buffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'3 4 declare global {5 // eslint-disable-next-line @typescript-eslint/no-namespace6 namespace jsx.JSX {21 unmodified lines28 'wbr',29 ]30 const booleanAttributes = ['checked', 'selected', 'disabled', 'readonly', 'multiple']31 32-const newHtmlEscapedString = (str: string): HtmlEscapedString => {33- const escapedString = new String(str) as HtmlEscapedString34- escapedString.isEscaped = true35- return escapedString32+const childrenToStringToBuffer = (children: Child[], buffer: Buffer): void => {33+ for (let i = 0, len = children.length; i < len; i++) {34+ const child = children[i]35+ if (typeof child === 'string') {36+ escapeToBuffer(child, buffer)37+ } else if (typeof child === 'boolean' || child === null || child === undefined) {38+ continue39+ } else if (child instanceof JSXNode) {40+ child.toStringToBuffer(buffer)41+ } else if (typeof child === 'number' || (child as any).isEscaped) {42+ buffer[0] += child43+ } else {44+ // `child` type is `Child[]`, so stringify recursively45+ childrenToStringToBuffer(child, buffer)46+ }47+ }48 }49 38-export { jsxFn as jsx }39-const jsxFn = (40- tag: string | Function,41- props: Record<string, any>,42- ...children: (string | HtmlEscapedString)[]43-): HtmlEscapedString => {44- if (typeof tag === 'function') {45- return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children })50+type Child = string | number | JSXNode | Child[]51+export class JSXNode implements HtmlEscaped {52+ tag: string | Function53+ props: Record<string, any>54+ children: Child[]55+ isEscaped: true = true56+ constructor(tag: string | Function, props: Record<string, any>, children: Child[]) {57+ this.tag = tag58+ this.props = props59+ this.children = children60 }61 48- let result = tag !== '' ? `<${tag}` : ''62+ toString(): string {63+ const buffer: Buffer = ['']64+ this.toStringToBuffer(buffer)65+ return buffer[0]66+ }67 50- const propsKeys = Object.keys(props || {})68+ toStringToBuffer(buffer: Buffer): void {69+ const tag = this.tag as string70+ const props = this.props71+ let { children } = this72 73+ buffer[0] += `<${tag}`74+75+ const propsKeys = Object.keys(props || {})76+77+ for (let i = 0, len = propsKeys.length; i < len; i++) {78+ const v = props[propsKeys[i]]52- for (let i = 0, len = propsKeys.length; i < len; i++) {53- const v = props[propsKeys[i]]54- if (typeof v === 'string') {55- result += ` ${propsKeys[i]}="${escape(v)}"`56- } else if (typeof v === 'number') {57- result += ` ${propsKeys[i]}="${v}"`58- } else if (v === null || v === undefined) {59- // Do nothing60- } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {61- if (v) {62- result += ` ${propsKeys[i]}=""`79+ if (typeof v === 'string') {80+ buffer[0] += ` ${propsKeys[i]}="`81+ escapeToBuffer(v, buffer)82+ buffer[0] += '"'83+ } else if (typeof v === 'number') {84+ buffer[0] += ` ${propsKeys[i]}="${v}"`85+ } else if (v === null || v === undefined) {86+ // Do nothing87+ } else if (typeof v === 'boolean' && booleanAttributes.includes(propsKeys[i])) {88+ if (v) {89+ buffer[0] += ` ${propsKeys[i]}=""`90+ }91+ } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {92+ if (children.length > 0) {93+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'94+ }95+96+ const escapedString = new String(v.__html) as HtmlEscapedString97+ escapedString.isEscaped = true98+ children = [escapedString]99+ } else {100+ buffer[0] += ` ${propsKeys[i]}="`101+ escapeToBuffer(v.toString(), buffer)102+ buffer[0] += '"'103 }64- } else if (propsKeys[i] === 'dangerouslySetInnerHTML') {65- if (children.length > 0) {66- throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'67- }104+ }105 69- children = [newHtmlEscapedString(v.__html)]70- } else {71- result += ` ${propsKeys[i]}="${escape(v.toString())}"`106+ if (emptyTags.includes(tag as string)) {107+ buffer[0] += '/>'108+ return109 }73- }110 75- if (emptyTags.includes(tag)) {76- result += '/>'77- return newHtmlEscapedString(result)78- }111+ buffer[0] += '>'112 80- if (tag !== '') {81- result += '>'113+ childrenToStringToBuffer(children, buffer)114+115+ buffer[0] += `</${tag}>`116 }117+}118 84- const flattenChildren = children.flat(Infinity)85- for (let i = 0, len = flattenChildren.length; i < len; i++) {86- const child = flattenChildren[i]87- if (typeof child === 'boolean' || child === null || child === undefined) {88- continue89- } else if (typeof child === 'object' && (child as any).isEscaped) {90- result += child119+class JSXFunctionNode extends JSXNode {120+ toStringToBuffer(buffer: Buffer): void {121+ const { children } = this122+123+ const res = (this.tag as Function).call(null, {124+ ...this.props,125+ children: children.length <= 1 ? children[0] : children,126+ })127+128+ if (res instanceof JSXNode) {129+ res.toStringToBuffer(buffer)130+ } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {131+ buffer[0] += res132 } else {92- result += escape(child.toString())133+ escapeToBuffer(res, buffer)134 }135 }136+}137 96- if (tag !== '') {97- result += `</${tag}>`138+class JSXFragmentNode extends JSXNode {139+ toStringToBuffer(buffer: Buffer): void {140+ childrenToStringToBuffer(this.children, buffer)141 }142+}143 100- return newHtmlEscapedString(result)144+export { jsxFn as jsx }145+const jsxFn = (146+ tag: string | Function,147+ props: Record<string, any>,148+ ...children: (string | HtmlEscapedString)[]149+): JSXNode => {150+ if (typeof tag === 'function') {151+ return new JSXFunctionNode(tag, props, children)152+ } else {153+ return new JSXNode(tag, props, children)154+ }155 }156 157 type FC<T = Record<string, any>> = (props: T) => HtmlEscapedString158 31 unmodified lines190 return (computed ||= component(props))191 }) as FC<T>192 }193 140-export const Fragment = (props: { key?: string; children?: any }): HtmlEscapedString => {141- return jsxFn('', {}, ...(props.children || []))194+export const Fragment = (props: { key?: string; children?: any }): JSXNode => {195+ return new JSXFragmentNode('', {}, props.children || [])196 }modified:src/middleware/jsx/jsx-dev-runtime.ts+2 added-2 removed
1123445678import type { HtmlEscapedString } from '../html'import { jsx } from '.'import type { JSXNode } from '.'
export function jsxDEV(tag: string | Function, props: Record<string, any>): HtmlEscapedString {export function jsxDEV(tag: string | Function, props: Record<string, any>): JSXNode { const children = props.children ?? [] delete props['children'] return jsx(tag, props, children)}modified:src/utils/html.test.ts+20 added-5 removed
112343456567891011121314151617181920212223import { escape } from './html'import { escape, escapeToBuffer } from './html'import type { Buffer } from './html'
describe('HTML utilities', () => {describe('HTML escape', () => { it('Should escape special characters', () => { expect(escape('I <b>think</b> this is good.')).toBe('I <b>think</b> this is good.') expect(escape('John "Johnny" Smith')).toBe('John "Johnny" Smith') describe('escape', () => { it('Should escape special characters', () => { expect(escape('I <b>think</b> this is good.')).toBe('I <b>think</b> this is good.') expect(escape('John "Johnny" Smith')).toBe('John "Johnny" Smith') }) })
describe('escapeToBuffer', () => { it('Should escape special characters', () => { let buffer: Buffer = [''] escapeToBuffer('I <b>think</b> this is good.', buffer) expect(buffer[0]).toBe('I <b>think</b> this is good.')
buffer = [''] escapeToBuffer('John "Johnny" Smith', buffer) expect(buffer[0]).toBe('John "Johnny" Smith') }) })})modified:src/utils/html.ts+54 added-10 removed
112343456789105678910121112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657export type HtmlEscapedString = string & { isEscaped: true }export type HtmlEscaped = { isEscaped: true }export type HtmlEscapedString = string & HtmlEscapedexport type Buffer = [string]
const entityMap: Record<string, string> = { '&': '&', '<': '<', '>': '>', '"': '"',}const escapeRe = new RegExp(`[${Object.keys(entityMap).join('')}]`, 'g')const replaceFn = (m: string) => entityMap[m]// The `escape` and `escapeToBuffer` implementations are based on code from the MIT licensed `react-dom` package.// https://github.com/facebook/react/blob/main/packages/react-dom/src/server/escapeTextForBrowser.js
const escapeRe = /[&<>"]/
export const escape = (str: string): string => { return str.replace(escapeRe, replaceFn) // This function is an alias for `escapeToBuffer`, // but returns immediately if `str` does not contain the character to be escaped. const match = str.search(escapeRe) if (match === -1) { return str }
const buffer: Buffer = [''] escapeToBuffer(str, buffer) return buffer[0]}
export const escapeToBuffer = (str: string, buffer: Buffer): void => { const match = str.search(escapeRe) if (match === -1) { buffer[0] += str return }
let escape let index let lastIndex = 0
for (index = match; index < str.length; index++) { switch (str.charCodeAt(index)) { case 34: // " escape = '"' break case 38: // & escape = '&' break case 60: // < escape = '<' break case 62: // > escape = '>' break default: continue }
buffer[0] += str.substring(lastIndex, index) + escape lastIndex = index + 1 }
buffer[0] += str.substring(lastIndex, index)}