Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Optimised renderToString and streamQueueAsString for performance (except it didn't...) #1504

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
196 changes: 196 additions & 0 deletions packages/inferno-server/__tests__/performance.server.jsx
@@ -0,0 +1,196 @@
import { renderToStaticMarkup, renderToString } from 'inferno-server';
import { Component, createFragment } from 'inferno';
import { createElement } from 'inferno-create-element';
import { ChildFlags } from 'inferno-vnode-flags';
import { hydrate } from 'inferno-hydrate';
//import { performance } from 'perf_hooks';

function WrappedInput(props) {
return <input type="text" value={props.value} />;
}

function WithChild(props) {
return <div>{props.children}</div>
}

describe('SSR Creation (JSX)', () => {
const testEntries = [
{
template: (props) => <div>{null}</div>,
},
{
template: (props) => (
<div>
{null}
<span>emptyValue: {null}</span>
</div>
),
},
{
template: (props) => <script src="foo" async />,
},
{
template: (props) => (
<div>
Hello world, {'1'}2{'3'}
</div>
),
},
{
template: (props) => <div>"Hello world"</div>,
},
{
template: (props) => <div>Hello world, {/* comment*/}</div>,
},
{
template: (props) => <div>{[null, '123', null, '456']}</div>,
},
{
template: (props) => <p children="foo">foo</p>,
},
{
template: (props) => <input value="bar" />,
},
{
template: (props) => <input value="bar" defaultValue="foo" />,
},
{
template: (props) => <input defaultValue="foo" />,
},
{
template: (props) => <input defaultValue={123} />,
},
{
template: (props) => <WrappedInput value="foo" />,
},
{
template: (props) => (
<select value="dog">
<option value="cat">A cat</option>
<option value="dog">A dog</option>
</select>
),
},
{
template: (props) => (
<div>
<div>{''}</div>
<div>{props.children}</div>
<p>Test</p>
</div>
),
},
{
template: (props) => <div style={{ 'background-color': 'red', 'border-bottom-color': 'green' }} />,
},
{
template: (props) => <div style={{ 'background-color': null, 'border-bottom-color': null }} />,
},
{
template: (props) => <div style={null}>{props.children}</div>,
},
{
template: (props) => createElement('div', null, 'Hello world <img src="x" onerror="alert(\'&XSS&\')">'),
},
{
template: (props) => <div style={{ opacity: 0.8 }} />,
},
{
template: (props) => <div style="opacity:0.8;">{props.children}</div>,
},
{
template: (props) => <div className={123} />,
},
{
template: (props) => <input defaultValue={123} />,
},
{
template: (props) => (
<div>
<br />
{props.children}
</div>
),
},
{
template: (props) => (
[
<p>1</p>,
<p>2</p>,
<p>3</p>
]
),
},
{
template: (props) => [],
},
{
template: (props) => (
<>
<p>1</p>
<p>2</p>
<p>3</p>
</> /* reset syntax highlighting */
),
},
{
template: (props) => (<></>), /* reset syntax highlighting */
},
{
template: (props) => (<>{props.children}</>), /* reset syntax highlighting */
}
];

function getVDom(depth) {
if (depth === 0) {
return null
}

return <WithChild>{testEntries.map((item) => item.template(<div>{getVDom(depth - 1)}</div>))}</WithChild>
}

it("Tests performance and memory consumption", () => {
let output
const vDom = getVDom(4);

const imax = 100;
const timing = [];
const memory = [];
for (let i = 0; i++ < imax;) {
const start = performance.now();
const startMem = process.memoryUsage();

for (let j = 0; j++ < 10;) {
output = renderToString(vDom);
}
const end = performance.now();
const endMem = process.memoryUsage();
timing.push((end - start) / 10);
memory.push({
heapTotal: (endMem.heapTotal - startMem.heapTotal) / 10 / 1024,
heapUsed: (endMem.heapUsed - startMem.heapUsed) / 10 / 1024,
external: (endMem.external - startMem.external) / 10 / 1024,
})
}
console.log("Timing: ", timing)
console.log("Memory delta: ", memory)

console.log("Average: ",
Math.round(timing.reduce((prev, curr, i, arr) => prev + curr / arr.length, 0) * 1000) / 1000 + "ms",
Math.round(memory.filter((i) => i.heapUsed > 0).reduce((prev, curr, i, arr) => prev + curr.heapUsed / arr.length, 0) * 10) / 10 + "kb",
Math.round(memory.reduce((prev, curr, i, arr) => prev + curr.heapUsed / arr.length, 0) * 10) / 10 + "kb"
)
console.log("(time/call – heap delta/call – heap delta overall")

expect(typeof output).toBe('string');
expect(output.length).toBeGreaterThan(1000);
expect(output).toContain('<option value="cat">A cat</option>')
/*
const container = document.createElement('div');
document.body.appendChild(container);
container.innerHTML = output;
expect(output).toBe(test.result);
document.body.removeChild(container);
*/
});
});
44 changes: 24 additions & 20 deletions packages/inferno-server/src/renderToString.queuestream.ts
Expand Up @@ -16,6 +16,10 @@ import {Readable} from 'stream';
import {renderStylesToString} from './prop-renderers';
import {createDerivedState, escapeText, isAttributeNameSafe, voidElements} from './utils';

function concat(...args: string[]): string {
return args.join('');
}

export class RenderQueueStream extends Readable {
public collector: any[] = [Infinity]; // Infinity marks the end of the stream
public promises: any[] = [];
Expand Down Expand Up @@ -184,15 +188,15 @@ export class RenderQueueStream extends Readable {
}
// If an element
} else if ((flags & VNodeFlags.Element) > 0) {
let renderedString = `<${type}`;
const tmpARR = [`<${type}`];
let html;
const isVoidElement = voidElements.has(type);
const className = vNode.className;

if (isString(className)) {
renderedString += ` class="${escapeText(className)}"`;
tmpARR.push(` class="${escapeText(className)}"`);
} else if (isNumber(className)) {
renderedString += ` class="${className}"`;
tmpARR.push(` class="${className}"`);
}

if (!isNull(props)) {
Expand All @@ -205,7 +209,7 @@ export class RenderQueueStream extends Readable {
break;
case 'style':
if (!isNullOrUndef(props.style)) {
renderedString += ` style="${renderStylesToString(props.style)}"`;
tmpARR.push(` style="${renderStylesToString(props.style)}"`);
}
break;
case 'children':
Expand All @@ -215,68 +219,68 @@ export class RenderQueueStream extends Readable {
case 'defaultValue':
// Use default values if normal values are not present
if (!props.value) {
renderedString += ` value="${isString(value) ? escapeText(value) : value}"`;
tmpARR.push(` value="${isString(value) ? escapeText(value) : value}"`);
}
break;
case 'defaultChecked':
// Use default values if normal values are not present
if (!props.checked) {
renderedString += ` checked="${value}"`;
tmpARR.push(` checked="${value}"`);
}
break;
default:
if (isAttributeNameSafe(prop)) {
if (isString(value)) {
renderedString += ` ${prop}="${escapeText(value)}"`;
tmpARR.push(` ${prop}="${escapeText(value)}"`);
} else if (isNumber(value)) {
renderedString += ` ${prop}="${value}"`;
tmpARR.push(` ${prop}="${value}"`);
} else if (value === true) {
renderedString += ` ${prop}`;
tmpARR.push(` ${prop}`);
}
}
break;
}
}
}
renderedString += `>`;
tmpARR.push(`>`);

if (String(type).match(/[\s\n\/='"\0<>]/)) {
throw renderedString;
throw tmpARR.join('');
}

// Voided element, push directly to queue
if (isVoidElement) {
this.addToQueue(renderedString, position);
this.addToQueue(tmpARR.join(''), position);
// Regular element with content
} else {
// Element has children, build them in
const childFlags = vNode.childFlags;

if (childFlags === ChildFlags.HasVNodeChildren) {
this.addToQueue(renderedString, position);
this.addToQueue(tmpARR.join(''), position);
this.renderVNodeToQueue(children, context, position);
this.addToQueue('</' + type + '>', position);
this.addToQueue(concat('</', type, '>'), position);
return;
} else if (childFlags === ChildFlags.HasTextChildren) {
this.addToQueue(renderedString, position);
this.addToQueue(tmpARR.join(''), position);
this.addToQueue(children === '' ? ' ' : escapeText(children + ''), position);
this.addToQueue('</' + type + '>', position);
this.addToQueue(concat('</', type, '>'), position);
return;
} else if (childFlags & ChildFlags.MultipleChildren) {
this.addToQueue(renderedString, position);
this.addToQueue(tmpARR.join(''), position);
for (let i = 0, len = children.length; i < len; ++i) {
this.renderVNodeToQueue(children[i], context, position);
}
this.addToQueue('</' + type + '>', position);
this.addToQueue(concat('</', type, '>'), position);
return;
}
if (html) {
this.addToQueue(renderedString + html + '</' + type + '>', position);
this.addToQueue(concat(tmpARR.join(''), html,'</', type, '>'), position);
return;
}
// Close element if it's not void
if (!isVoidElement) {
this.addToQueue(renderedString + '</' + type + '>', position);
this.addToQueue(concat(tmpARR.join(''), '</', type, '>'), position);
}
}
// Push text directly to queue
Expand Down