Performance
Your view runs next to the webapp on the phone of the person and receives every change of a world that can change many times a second (a score, a camera picture, a long conversation). The kit sends your view only what changed. Your code keeps each change cheap by skipping the work for what did not change, by following fast data separately and by keeping React from rendering more than it must.
What the webapp sends to your view
When your view connects, the webapp sends it the whole world once. After that the webapp sends only the difference at each change (a new message, the one value of data that changed or the new now). A large picture in data is sent once and not again with every message.
Your code never handles these partial changes because subscribe and world.get() always give you the whole world rebuilt from them.
When the kit rebuilds the world, a value of data that did not change stays the same object as before. A single === tells you whether there is anything new to render:
let lastBoard = null;
world.subscribe((node) => {
if (node.data.board !== lastBoard) {
lastBoard = node.data.board;
drawBoard(lastBoard); // only when the board really changed
}
});A fake world also keeps each unchanged value as the same object.
Subscribe once
world.subscribe(listener) adds a listener that runs at every change. Call it once when your page starts and render everything from that listener.
Pitfall
Do not call subscribe inside a listener, in a click handler or each time a panel opens without stopping the previous listener. Each call adds a listener and after ten such calls every change runs your rendering code ten times. A part of your page with its own listener keeps the function returned by subscribe and calls it when the part goes away:
const stop = world.subscribe((node) => drawPanel(node));
// ...when the panel closes:
stop();In React call useWorld once in your top component and pass world down as a prop (Thinking in views).
Keep the work in subscribe small
The listener runs at every change of the world (every message and every new value) and a world with a timer in its data can call it ten times a second. Three rules keep this work small:
- Render only what changed. Compare with what you rendered last (
===for values ofdata,message.idfor messages) and leave the rest of the page untouched. - Do not rebuild the whole page. Replacing hundreds of elements at every change is the most common cause of a slow view. Update the few elements whose value changed.
- Do not recompute what has not changed. Sort a long list or parse a large value when that value changes instead of at every change of the world.
In the example below a list of 300 rooms that never changes sits next to a speed that changes ten times a second. The view renders the list once and afterwards only the speed:
import { memo } from 'react';
import { useWorld } from './useWorld.js';
// A fake world with a long list that never changes, and a speed that changes ten times a second.
const ROOMS = Array.from({ length: 300 }, (_, index) => `Room ${index + 1}`);
const track = {
name: 'Race track',
data: {
rooms: ROOMS,
speed: { every: 100, value: (time) => 100 + Math.round(20 * Math.sin(time / 500)) },
},
};
// Only for this demo: how many times React drew the list. Leave it out of your view.
let times = 0;
// Costly: 300 elements. `memo` draws it again only when `rooms` is another object.
// A value of the world that did not change stays the same object as before.
const RoomList = memo(function RoomList({ rooms }) {
times += 1;
return (
<>
<p>{times === 1 ? 'The list was drawn once.' : `The list was drawn ${times} times.`}</p>
<ul style={{ height: 120, overflow: 'auto' }}>
{rooms.map((room) => <li key={room}>{room}</li>)}
</ul>
</>
);
});
export default function App() {
// While building: the fake world. In the webapp: useWorld()
const { world, error } = useWorld({ fake: { world: track } });
if (error) return <p>Could not connect ({error.code}).</p>;
if (!world) return <p>Connecting…</p>;
// Cheap: one line of text, at every change.
return (
<>
<p>Speed: {world.data.speed} km/h</p>
<RoomList rooms={world.data.rooms} />
</>
);
}import { connectToHost } from '@unaiverse/gui-kit';
// A fake world with a long list that never changes, and a speed that changes ten times a second.
const ROOMS = Array.from({ length: 300 }, (_, index) => `Room ${index + 1}`);
const track = {
name: 'Race track',
data: {
rooms: ROOMS,
speed: { every: 100, value: (time) => 100 + Math.round(20 * Math.sin(time / 500)) },
},
};
// While building: the fake world. In the webapp: const world = await connectToHost();
const world = await connectToHost({ fake: { world: track } });
const speed = document.createElement('p');
const drawn = document.createElement('p');
const list = document.createElement('ul');
list.style.cssText = 'height: 120px; overflow: auto;';
document.body.append(speed, drawn, list);
// The list as it was last drawn, and how many times it was drawn.
let drawnRooms = null;
let times = 0;
world.subscribe((node) => {
// Cheap: one line of text, at every change.
speed.textContent = `Speed: ${node.data.speed} km/h`;
// Costly: 300 elements. A value that did not change is the same object as before.
// One comparison then tells whether there is anything to draw.
if (node.data.rooms === drawnRooms) return;
drawnRooms = node.data.rooms;
times += 1;
drawn.textContent = times === 1 ? 'The list was drawn once.' : `The list was drawn ${times} times.`;
list.replaceChildren(...drawnRooms.map((room) => {
const item = document.createElement('li');
item.textContent = room;
return item;
}));
});Fast data: onData
world.onData(name, listener) follows a single value that changes fast (a speed, a camera picture, a position) and calls its listener only when that value changes (Follow one value):
world.onData('speed', (speed) => {
speedText.textContent = `${speed} km/h`;
});On a canvas, draw at most once per screen frame and always with the newest value. When two values arrive between two frames only the second is drawn:
let latest = null;
let isScheduled = false;
world.onData('camera', (picture) => {
latest = picture;
if (isScheduled) return;
isScheduled = true;
requestAnimationFrame(() => {
isScheduled = false;
drawPicture(latest);
});
});The recipe Follow fast data without slowing down combines both techniques.
Pictures
Pictures in data and in messages are data URIs (sometimes URLs) ready for img.src. Large pictures are costly to decode and to lay out:
- Write
srconly when the picture changed. Writing it again, even with the same string, can make the browser decode the picture again. Compare first (if (img.src !== node.data.photo) img.src = node.data.photo) or letonDatacall your code only when the picture changes. - Give pictures their size (
widthandheightor a CSSaspect-ratio) to keep the layout from shifting when they load. - Let the browser decode them off the main thread with
img.decoding = 'async'. - Add
loading="lazy"to the pictures of a long conversation. The browser then loads a picture out of sight only when the person scrolls near it. - Draw a picture that changes many times a second (a camera) on a
canvasonce per frame as shown above.
In React
At every change of the world useWorld re-renders your component and all its children. The children whose values did not change render again as well. Because unchanged values of data keep their identity, the memoization tools of React skip those parts:
memofor a costly component. Wrap the component that renders a large value and pass it that value (<Board board={world.data.board} />). Like the list of rooms in the example above, React skips it while the board is the same object.Pass memoized components the values they render and not the whole world.
worldis a new object at every change andmemonever skips a component that takesworldas a prop.Pass the fields of a message rather than the message.
memocompares the props of a row and the message objects are new at every change while their fields are not.memocan skip a row that takestext,fromandstatusinstead of the message object:jsxconst MessageRow = memo(function MessageRow({ from, text, status }) { return <p>{from}: {text} {status === 'failed' && '(not delivered)'}</p>; }); {world.messages.map((message) => ( <MessageRow key={message.id} from={message.from} text={message.text} status={message.status} /> ))}Keys from
message.idand never from the index. With stable ids React adds only the new rows.Isolate the fast part. Keep the component that shows a value changing ten times a second small and memoize its costly siblings.
useMemofor what you compute from a value with that value as the dependency (useMemo(() => sortRooms(world.data.rooms), [world.data.rooms])).Never
worldas a dependency of an effect. The effect would run at every change. Depend on the values the effect uses.
Long conversations
A world that sends many messages gives you a long messages list and rendering a thousand rows is slow on a phone. Keep the rendered list short:
- render the newest messages (
world.messages.slice(-100)) with a button that shows more - load older messages with
world.loadMore()only when the person asks (Load older messages) - for very long lists use a virtual list that renders only the visible rows.
Your view keeps running
When the person switches to the UNaIVERSE view of the world, the webapp hides your view without closing it. The hidden view stays loaded and keeps receiving every change of the world in order to be ready when the person switches back. A person in a world can also have the views of a few agents open at the same time.
A hidden view should do no work while nothing happens (no timers that re-render without a change, no endless animations). Render when the world changes and animate with requestAnimationFrame instead of setInterval.
Measure
Record a few seconds with the Performance panel of the browser developer tools (on your page alone or on the webapp with your view inside) and look for long tasks after each change. In React the Profiler of the React developer tools shows which components rendered and why. A laptop is much faster than most phones. Do the final test on a real phone.
Next steps
- Layout and style inside the webapp: the place of your view in the webapp.
- Reference:
subscribe,onData,loadMore. - Recipes: Follow fast data without slowing down, A chart of a number over time.