-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
665 lines (578 loc) · 23.4 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Incremental Rendering Tests</title>
<link rel="stylesheet" href="normalize.css">
<style>
* {
box-sizing: border-box;
}
body {
font-family: -apple-system,BlinkMacSystemFont,segoe ui,Helvetica,Arial,sans-serif,apple color emoji,segoe ui emoji,segoe ui symbol;
}
.main {
display: flex;
flex-direction: column;
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
header {
display: flex;
padding: 0.8rem;
}
.links {
flex-shrink: 0;
display: flex;
flex-direction: column;
justify-content: space-around;
margin-left: 0.8rem;
opacity: 0.8;
}
.links img {
width: 1.6rem;
}
.description {
flex-grow: 1;
}
.description p,
.desc p
{
margin: 0.6em 0;
line-height: 1.3em;
}
.description p:first-child,
.desc p:first-child
{
margin-top: 0;
}
.description p:last-child,
.desc p:last-child
{
margin-bottom: 0;
}
.cases {
display: flex;
flex-grow: 1;
overflow-x: auto;
border-top: 1px solid #ccc;
}
.cases > div {
width: 22rem;
flex-shrink: 0;
padding: 0 0.8rem 0.8rem;
overflow-y: auto;
}
.cases > div:not(:last-child) {
border-right: 1px solid #ccc;
}
input {
width: 100%;
}
h2 {
margin-bottom: 0.4em;
}
h4 {
margin: 0.8em 0 0.4em;
}
.desc {
margin: 0.4em 0 0.8em;
}
.highlight {
background-color: yellow;
border: 1px solid #999;
border-radius: 3px;
}
img {
max-width: 100%;
}
</style>
<!-- Production libs -->
<script src="react.production.min.js"></script>
<script src="react-dom.production.min.js"></script>
<script src="vue.global.prod.js"></script>
<!-- Development libs -->
<!--
<script src="react.development.js"></script>
<script src="react-dom.development.js"></script>
<script src="vue.global.js"></script>
-->
<script src="svelte-app.js"></script>
<script>
const e = React.createElement;
const MAX_INCREMENTAL = 10;
</script>
</head>
<body>
<div class="main">
<header>
<div class="description">
<p>
An experiment to see if anything I do with popular JavaScript frameworks can match the performance of the search on the very large <a href="https://hero.handmade.network/episode/code">Handmade Hero episode guide</a>. View the source code for details on each algorithm.
</p>
<p>
All of these execute the same search in the same amount of time. The differences you see here are purely from render times and DOM update times.
</p>
<p>
<strong>WARNING!</strong> Some of these are extremely heavy and may lock up your tab or your browser.
</p>
</div>
<div class="links">
<a target="_blank" href="https://github.com/bvisness/incremental" title="View on GitHub">
<img src="github.svg">
</a>
<a target="_blank" href="https://twitter.com/its_bvisness" title="Follow me on Twitter">
<img src="twitter.svg">
</a>
</div>
</header>
<div class="cases">
<div>
<h2>Vanilla (Naive)</h2>
<div class="desc">
<p>
This algorithm manually creates and inserts DOM nodes. This demonstrates the baseline performance for the "naive" method where all results are rendered at once.
</p>
<p>
This method is generally fast enough that the bottleneck is the browser calculating layout after DOM operations are finished. It is still slow enough, though, to demonstrate the need for a smarter approach.
</p>
</div>
<div id="vn-container">
<input id="vn-query">
<div id="vn-results"></div>
</div>
</div>
<div>
<h2>Vanilla (Incremental)</h2>
<div class="desc">
<p>
This algorithm incrementally renders items by adding a few search results to the DOM each frame. This is the approach used on the actual Handmade Hero episode guide, and it results in a consistently responsive UI.
</p>
</div>
<div id="vi-container">
<input id="vi-query">
<div id="vi-results"></div>
</div>
</div>
<div>
<h2>React (Naive)</h2>
<div class="desc">
<p>
This renders all search results at once using React. It incurs framework overhead on top of the usual DOM work, increasing mount times and adding a diff cost when many search results are already rendered.
</p>
</div>
<div id="rn-container"></div>
</div>
<div>
<h2>React (Naive, Concurrent Mode)</h2>
<div class="desc">
<p>
This is the same as the previous, but rendering using React's experimental concurrent mode. No significant difference is visible; apparently the update work is still synchronous enough to block user input.
</p>
</div>
<div id="rn-c-container"></div>
</div>
<div>
<h2>React (Incremental)</h2>
<div class="desc">
<p>
This renders results incrementally using React, gradually increasing the size of the result set. React does ok, but the increasing framework overhead (including diffing) grows as more items render.
</p>
</div>
<div id="ri-container"></div>
</div>
<div>
<h2>React (Incremental, Concurrent Mode)</h2>
<div class="desc">
<p>
This is the same as the previous but with concurrent mode. This time the user experience is noticeably better, with less hitching on user input. To my eye, the initial performance of this method is nearly as good as vanilla, but the diff cost results in hitching after a large result set has loaded.
</p>
</div>
<div id="ri-c-container"></div>
</div>
<div>
<h2>Vue (Naive)</h2>
<div class="desc">
<p>
This renders all results at once using Vue. Vue was by far the worst performer in these tests - by my timing, Vue is generally about 2x slower than React and 3x slower than vanilla.
</p>
</div>
<div id="vue-n-container">
<input v-model="query">
<div>
<div v-for="r in results" :key="r.episode.day">
<search-result :result="r" />
</div>
</div>
</div>
</div>
<div>
<h2>Vue (Incremental)</h2>
<div class="desc">
<p>
I'll say this: Vue doesn't get any faster here.
</p>
</div>
<div id="vue-i-container">
<input v-model="query">
<div>
<div v-for="r in resultSlice" :key="r.episode.day">
<search-result :result="r" />
</div>
</div>
</div>
</div>
<div>
<h2>Svelte (Naive)</h2>
<div class="desc">
<p>
Despite Svelte's claims of speed, it was generally middle of the pack in terms of performance. Here I measured it to be about 1.5x slower than React.
</p>
<p>
However, the performance of Svelte here seems wildly variable, and some user inputs seem to allocate insane amounts of memory.
</p>
</div>
<div id="svelte-n-container"></div>
</div>
<div>
<h2>Svelte (Incremental)</h2>
<div class="desc">
<p>
Svelte remained middle of the pack here as well.
</p>
</div>
<div id="svelte-i-container"></div>
</div>
</div>
</div>
<script src="project.js"></script>
<script>
var project = getProject();
var renderHandle;
/*
Searches the episode information and returns all the results.
Used by all test cases.
Adapted from the original: https://handmade.network/static/annotations/cinera_search.js
*/
function runSearch(queryStr) {
var numEpisodes = 0;
var numMarkers = 0;
var totalSeconds = 0;
// NOTE(matt): Function defined within runSearch() so that we can modify numEpisodes, numMarkers and totalSeconds
function runSearchInterior(resultsToRender, query, episode)
{
var matches = [];
for (var k = 0; k < episode.markers.length; ++k) {
query.lastIndex = 0;
var result = query.exec(episode.markers[k].text);
if (result && result[0].length > 0) {
numMarkers++;
matches.push(episode.markers[k]);
if (k < episode.markers.length-1) {
totalSeconds += episode.markers[k+1].totalTime - episode.markers[k].totalTime;
}
}
}
if (matches.length > 0) {
numEpisodes++;
resultsToRender.push({
query: query,
episode: episode,
matches: matches
});
}
}
var results = [];
if (queryStr && queryStr.length > 0) {
var query = new RegExp(queryStr.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'), 'gi');
if(project.parsed && !project.filteredOut && project.episodes.length > 0) {
for(var j = 0; j < project.episodes.length; ++j) {
var episode = project.episodes[j];
runSearchInterior(results, query, episode);
}
}
}
var totalTime = Math.floor(totalSeconds/60/60) + "h " + Math.floor(totalSeconds/60)%60 + "m " + totalSeconds%60 + "s ";
return [results, "Found: " + numEpisodes + " episodes, " + numMarkers + " markers, " + totalTime + "total."];
}
/*
Renders a single search result.
*/
function renderResultVanilla(r) {
const resultEl = document.createElement('div');
const header = document.createElement('h4');
header.innerText = r.episode.title;
resultEl.appendChild(header);
for (const m of r.matches) {
const p = document.createElement('p');
p.appendChild(document.createTextNode(`${m.prettyTime} `));
let startIndex = 0;
for (const highlightMatch of m.text.matchAll(r.query)) {
const text = m.text.slice(startIndex, highlightMatch.index);
p.appendChild(document.createTextNode(text));
const span = document.createElement('span');
span.classList.add('highlight');
span.innerText = highlightMatch[0];
p.appendChild(span);
startIndex = highlightMatch.index + highlightMatch[0].length;
}
const remainingText = m.text.slice(startIndex);
p.appendChild(document.createTextNode(remainingText));
resultEl.appendChild(p);
}
return resultEl;
}
/*
Renders results as straightforwardly as possible.
*/
function renderNaive(results) {
document.querySelector('#vn-results').innerHTML = '';
for (const r of results) {
document.querySelector('#vn-results').appendChild(renderResultVanilla(r));
}
}
/*
Renders results incrementally, processing and adding a chunk of
items to the DOM at a time.
*/
function renderIncremental(results, i = 0) {
var numItems = 0;
if (i === 0) {
document.querySelector('#vi-results').innerHTML = '';
clearTimeout(renderHandle);
}
if (i < results.length) {
rendering = true;
while (numItems < MAX_INCREMENTAL && i < results.length) {
document.querySelector('#vi-results').appendChild(renderResultVanilla(results[i]));
numItems++;
i++;
}
renderHandle = setTimeout(() => renderIncremental(results, i), 0);
} else {
rendering = false;
console.log('done with incremental render');
}
}
document.querySelector('#vn-query').addEventListener('input', e => {
const [results, summary] = runSearch(e.target.value);
renderNaive(results);
});
document.querySelector('#vi-query').addEventListener('input', e => {
const [results, summary] = runSearch(e.target.value);
renderIncremental(results);
});
/*
A React component that renders a result and all its matches.
*/
function SearchResult({ result }) {
return e(React.Fragment, {},
e('h4', {}, result.episode.title),
result.matches.map(m => (
e(SearchResultMatch, {key: m.prettyTime, result: result, match: m})
)),
);
}
/*
A React component that renders a specific matching annotation,
with highlights.
*/
function SearchResultMatch({ result, match }) {
const children = [];
children.push(`${match.prettyTime} `);
let startIndex = 0;
for (const highlightMatch of match.text.matchAll(result.query)) {
children.push(match.text.slice(startIndex, highlightMatch.index));
children.push(e('span', {className: 'highlight'}, highlightMatch[0]));
startIndex = highlightMatch.index + highlightMatch[0].length;
}
children.push(match.text.slice(startIndex));
return e('p', {}, ...children);
}
/*
Renders items using React as straightforwardly as possible.
*/
function ReactNaive() {
const [query, setQuery] = React.useState('');
function handleChange(e) {
setQuery(e.target.value);
}
const [results, summary] = runSearch(query);
return e(React.Fragment, {},
e('input', {value: query, onChange: handleChange}),
e('div', {}, results.map(r => (
e('div', {key: r.episode.day},
e(SearchResult, {result: r}),
)
))),
);
}
ReactDOM.render(e(ReactNaive), document.querySelector('#rn-container'));
ReactDOM.createRoot(document.querySelector('#rn-c-container')).render(e(ReactNaive));
/*
Renders items incrementally using React.
*/
function ReactIncremental() {
const [query, setQuery] = React.useState('');
const [results, setResults] = React.useState([]);
const [maxIndex, setMaxIndex] = React.useState(0);
const renderHandle = React.useRef(null);
function handleChange(e) {
setQuery(e.target.value);
setMaxIndex(MAX_INCREMENTAL);
}
React.useEffect(() => {
clearTimeout(renderHandle.current);
const [newResults, newSummary] = runSearch(query);
setResults(newResults);
}, [query]);
React.useEffect(() => {
if (maxIndex < results.length) {
const handle = setTimeout(() => setMaxIndex(maxIndex + MAX_INCREMENTAL), 0);
renderHandle.current = handle;
} else {
console.log('done with incremental render');
}
});
const resultSlice = results.slice(0, Math.min(maxIndex, results.length));
return e(React.Fragment, {},
e('input', {value: query, onChange: handleChange}),
e('div', {}, resultSlice.map(r => (
e('div', {key: r.episode.day},
e(SearchResult, {result: r}),
)
))),
);
}
ReactDOM.render(e(ReactIncremental), document.querySelector('#ri-container'));
ReactDOM.createRoot(document.querySelector('#ri-c-container')).render(e(ReactIncremental));
// Render items using Vue as straightforwardly as possible.
{
const app = Vue.createApp({
data() {
return {
query: '',
};
},
computed: {
results() {
const [results, summary] = runSearch(this.query);
return results;
},
},
});
app.component('search-result', {
props: ['result'],
template: `
<h4>{{ result.episode.title }}</h4>
<search-result-match v-for="m in result.matches" :key="m.prettyTime" :result="result" :match="m" />
`
});
app.component('search-result-match', {
props: ['result', 'match'],
computed: {
pieces() {
const { result, match } = this;
const pieces = [];
let startIndex = 0;
for (const highlightMatch of match.text.matchAll(result.query)) {
pieces.push(match.text.slice(startIndex, highlightMatch.index));
pieces.push(highlightMatch[0]);
startIndex = highlightMatch.index + highlightMatch[0].length;
}
pieces.push(match.text.slice(startIndex));
return pieces;
},
},
template: `
<p>
{{ match.prettyTime }}
<template v-for="(piece, i) in pieces">
<template v-if="i % 2 === 0">{{ piece }}</template>
<span v-else class="highlight">{{ piece }}</span>
</template>
</p>
`
});
app.mount('#vue-n-container');
}
// Render items incrementally using Vue
{
const app = Vue.createApp({
data() {
return {
query: '',
results: [],
maxIndex: 0,
renderHandle: null,
};
},
watch: {
query(query) {
clearTimeout(this.renderHandle);
const [newResults, newSummary] = runSearch(query);
this.results = newResults;
this.maxIndex = MAX_INCREMENTAL;
},
},
updated() {
if (this.maxIndex < this.results.length) {
const handle = setTimeout(() => {
this.maxIndex += MAX_INCREMENTAL;
}, 0);
this.renderHandle = handle;
} else {
console.log('done with incremental render');
}
},
computed: {
resultSlice() {
return this.results.slice(0, Math.min(this.maxIndex, this.results.length));
},
},
});
app.component('search-result', {
props: ['result'],
template: `
<h4>{{ result.episode.title }}</h4>
<search-result-match v-for="m in result.matches" :key="m.prettyTime" :result="result" :match="m" />
`
});
app.component('search-result-match', {
props: ['result', 'match'],
computed: {
pieces() {
const { result, match } = this;
const pieces = [];
let startIndex = 0;
for (const highlightMatch of match.text.matchAll(result.query)) {
pieces.push(match.text.slice(startIndex, highlightMatch.index));
pieces.push(highlightMatch[0]);
startIndex = highlightMatch.index + highlightMatch[0].length;
}
pieces.push(match.text.slice(startIndex));
return pieces;
},
},
template: `
<p>
{{ match.prettyTime }}
<template v-for="(piece, i) in pieces">
<template v-if="i % 2 === 0">{{ piece }}</template>
<span v-else class="highlight">{{ piece }}</span>
</template>
</p>
`
});
app.mount('#vue-i-container');
}
// Render items using Svelte as straightforwardly as possible.
new svelteApp.SvelteNaive({ target: document.querySelector('#svelte-n-container') });
// Render items incrementally using Svelte.
new svelteApp.SvelteIncremental({ target: document.querySelector('#svelte-i-container') });
</script>
</body>
</html>