Repository navigation
perf: add benchmark and improve performance #64
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,162 @@ | ||
| import { spawn } from 'node:child_process'; | ||
| import { mkdtempSync, rmSync } from 'node:fs'; | ||
| import { tmpdir } from 'node:os'; | ||
| import path from 'node:path'; | ||
| import { fileURLToPath } from 'node:url'; | ||
| import { setTimeout as sleep } from 'node:timers/promises'; | ||
|
|
||
| const root = fileURLToPath(new URL('..', import.meta.url)); | ||
| const previewPort = 4180; | ||
| const debugPort = 9230; | ||
| const base = `http://localhost:${previewPort}`; | ||
| const chromeBin = process.env.CHROME ?? 'google-chrome'; | ||
|
|
||
| const profiles = { | ||
| fast : null, | ||
| mobile: { cpu: 4, latency: 100, downloadMbps: 10, uploadMbps: 5 }, | ||
| }; | ||
|
|
||
| const steps = [ | ||
| { name: 'load home' , load : '/' , ready: '.post-item' }, | ||
| { name: 'click first post', click: '.post-item a[href$=".html"]', ready: '.markdown-body' }, | ||
| { name: 'reload post' , reload: true , ready: '.markdown-body' }, | ||
| { name: 'click logo' , click: 'a.logo' , ready: '.post-item' }, | ||
| { name: 'click tags' , click: 'a[href="/tags"]' , ready: '.tag-cloud-item' }, | ||
| { name: 'click first tag' , click: '.tag-cloud-item' , ready: '.post-item' }, | ||
| { name: 'history back' , back : true , ready: '.tag-cloud-item' }, | ||
| { name: 'click about' , click: 'a[href="/about"]' , ready: '.markdown-body' }, | ||
| ]; | ||
|
|
||
| const selectors = [...new Set(steps.map(step => step.ready))]; | ||
|
|
||
| const probe = ` | ||
| window.__marks = {}; | ||
| new MutationObserver(() => { | ||
| for (const selector of ${JSON.stringify(selectors)}) { | ||
| if (!window.__marks[selector] && document.querySelector(selector)) { | ||
| window.__marks[selector] = performance.timeOrigin + performance.now(); | ||
| } | ||
| } | ||
| }).observe(document, { childList: true, subtree: true }); | ||
| `; | ||
|
|
||
| const waitUntil = async (check, label, timeout = 30000) => { | ||
| const deadline = Date.now() + timeout; | ||
|
|
||
| while (Date.now() < deadline) { | ||
| const value = await check().catch(() => null); | ||
| if (value) { | ||
| return value; | ||
| } | ||
| await sleep(10); | ||
| } | ||
| throw new Error(`timeout: ${label}`); | ||
| }; | ||
|
|
||
| const connect = async url => { | ||
| const ws = new WebSocket(url); | ||
| const pending = new Map(); | ||
| let id = 0; | ||
|
|
||
| await new Promise((resolve, reject) => { | ||
| ws.onopen = resolve; | ||
| ws.onerror = reject; | ||
| }); | ||
|
|
||
| ws.onmessage = ({ data }) => { | ||
| const message = JSON.parse(data); | ||
| pending.get(message.id)?.(message); | ||
| pending.delete(message.id); | ||
| }; | ||
|
|
||
| const send = (method, params = {}) => new Promise((resolve, reject) => { | ||
| id += 1; | ||
| pending.set(id, message => (message.error ? reject(new Error(message.error.message)) : resolve(message.result))); | ||
| ws.send(JSON.stringify({ id, method, params })); | ||
| }); | ||
|
|
||
| const evaluate = async expression => (await send('Runtime.evaluate', { expression, returnByValue: true })).result.value; | ||
|
|
||
| return { send, evaluate, close: () => ws.close() }; | ||
| }; | ||
|
|
||
| const runProfile = async (name, throttle) => { | ||
| const userDir = mkdtempSync(path.join(tmpdir(), 'bench-chrome-')); | ||
| const chrome = spawn(chromeBin, [ | ||
| '--headless=new', | ||
| `--remote-debugging-port=${debugPort}`, | ||
| `--user-data-dir=${userDir}`, | ||
| '--no-first-run', | ||
| '--no-default-browser-check', | ||
| 'about:blank', | ||
| ], { stdio: 'ignore' }); | ||
|
|
||
| try { | ||
| const target = await waitUntil(async () => { | ||
| const targets = await (await fetch(`http://127.0.0.1:${debugPort}/json/list`)).json(); | ||
| return targets.find(item => item.type === 'page'); | ||
| }, 'chrome'); | ||
|
|
||
| const page = await connect(target.webSocketDebuggerUrl); | ||
|
|
||
| await page.send('Page.enable'); | ||
| await page.send('Network.enable'); | ||
| await page.send('Network.setBlockedURLs', { urls: ['*googletagmanager.com*', '*google-analytics.com*'] }); | ||
| await page.send('Page.addScriptToEvaluateOnNewDocument', { source: probe }); | ||
|
|
||
| if (throttle) { | ||
| await page.send('Emulation.setCPUThrottlingRate', { rate: throttle.cpu }); | ||
| await page.send('Network.emulateNetworkConditions', { | ||
| offline : false, | ||
| latency : throttle.latency, | ||
| downloadThroughput: (throttle.downloadMbps * 1024 * 1024) / 8, | ||
| uploadThroughput : (throttle.uploadMbps * 1024 * 1024) / 8, | ||
| }); | ||
| } | ||
|
|
||
| for (const step of steps) { | ||
| const inPage = step.click || step.back; | ||
| await page.evaluate(inPage ? 'window.__marks = {}' : 'window.__stale = true').catch(() => null); | ||
| const start = Date.now(); | ||
|
|
||
| if (step.load) { | ||
| await page.send('Page.navigate', { url: `${base}${step.load}` }); | ||
| } else if (step.reload) { | ||
| await page.send('Page.reload'); | ||
| } else if (step.back) { | ||
| await page.evaluate('history.back()'); | ||
| } else { | ||
| await page.evaluate(`document.querySelector(${JSON.stringify(step.click)}).click()`); | ||
| } | ||
|
|
||
| const ready = `!window.__stale && window.__marks[${JSON.stringify(step.ready)}]`; | ||
| const end = await waitUntil(() => page.evaluate(ready), step.name); | ||
| console.log(`${name.padEnd(7)} ${step.name.padEnd(16)} ${String(Math.round(end - start)).padStart(5)}`); | ||
| await sleep(300); | ||
| } | ||
|
|
||
| page.close(); | ||
| } finally { | ||
| chrome.kill(); | ||
| await sleep(300); | ||
| rmSync(userDir, { recursive: true, force: true }); | ||
| } | ||
| }; | ||
|
|
||
| const preview = spawn(path.join(root, 'node_modules/.bin/vite'), ['preview', '--port', String(previewPort), '--strictPort'], { | ||
| cwd : root, | ||
| stdio: 'ignore', | ||
| }); | ||
|
|
||
| try { | ||
| await waitUntil(async () => (await fetch(base)).ok, 'vite preview'); | ||
|
|
||
| console.log('navigation: action -> content visible, vite preview + headless chrome'); | ||
| console.log(`${'profile'.padEnd(7)} ${'step'.padEnd(16)} ${'ms'.padStart(5)}`); | ||
|
|
||
| for (const [name, throttle] of Object.entries(profiles)) { | ||
| await runProfile(name, throttle); | ||
| } | ||
| } finally { | ||
| preview.kill(); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| import { readdirSync, readFileSync } from 'node:fs'; | ||
| import { fileURLToPath } from 'node:url'; | ||
| import { renderMarkdown } from '../src/components/MarkdownRenderer/markdown.js'; | ||
|
|
||
| const publicDir = fileURLToPath(new URL('../public/', import.meta.url)); | ||
|
|
||
| const files = [ | ||
| 'about.md', | ||
| ...readdirSync(`${publicDir}posts`, { recursive: true }) | ||
| .filter(file => file.endsWith('.md')) | ||
| .sort() | ||
| .map(file => `posts/${file}`), | ||
| ]; | ||
|
|
||
| const results = files.map(file => ({ | ||
| name : file.split('/').pop().replace(/\.md$/, ''), | ||
| source: readFileSync(`${publicDir}${file}`, 'utf8'), | ||
| })); | ||
|
|
||
| for (const pass of ['cold', 'warm']) { | ||
| for (const result of results) { | ||
| const start = performance.now(); | ||
| const post = await renderMarkdown(result.source); | ||
|
|
||
| result[pass] = performance.now() - start; | ||
| result.kb = JSON.stringify(post).length / 1024; | ||
| } | ||
| } | ||
|
|
||
| const width = Math.max(...results.map(result => result.name.length)); | ||
| const sum = key => results.reduce((total, result) => total + result[key], 0); | ||
| const row = (name, cold, warm, kb) => console.log( | ||
| `${name.padEnd(width)} ${String(cold).padStart(7)} ${String(warm).padStart(7)} ${String(kb).padStart(7)}` | ||
| ); | ||
|
|
||
| console.log('render: markdown -> json at build time'); | ||
| row('file', 'cold ms', 'warm ms', 'json KB'); | ||
|
|
||
| for (const result of results) { | ||
| row(result.name, Math.round(result.cold), Math.round(result.warm), result.kb.toFixed(1)); | ||
| } | ||
|
|
||
| row('total', Math.round(sum('cold')), Math.round(sum('warm')), sum('kb').toFixed(1)); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛑 Logic Error: Both
fastandmobileprofiles use the same hardcodeddebugPort = 9230. EachrunProfilespawns its own Chrome process against that port. If the Chrome process from the first profile is still releasing the port during the 300 ms grace sleep, the second Chrome will fail to bind on the same port, causing thewaitUntilfor'chrome'to silently poll the previous (or a failed) debug endpoint and either return stale targets or timeout. Consider either passing a unique port per profile or ensuring the port is free before spawning the next Chrome instance.