index.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. // @ts-check
  2. import path from 'node:path'
  3. import { parseArgs } from 'node:util'
  4. import { mkdir, rm, writeFile } from 'node:fs/promises'
  5. import Vue from '@vitejs/plugin-vue'
  6. import { build } from 'vite'
  7. import connect from 'connect'
  8. import sirv from 'sirv'
  9. import { launch } from 'puppeteer'
  10. import colors from 'picocolors'
  11. import { exec, getSha } from '../../scripts/utils.js'
  12. import process from 'node:process'
  13. import readline from 'node:readline'
  14. // Thanks to https://github.com/krausest/js-framework-benchmark (Apache-2.0 license)
  15. const {
  16. values: {
  17. skipLib,
  18. skipApp,
  19. skipBench,
  20. vdom,
  21. noVapor,
  22. port: portStr,
  23. count: countStr,
  24. warmupCount: warmupCountStr,
  25. noHeadless,
  26. noMinify,
  27. reference,
  28. },
  29. } = parseArgs({
  30. allowNegative: true,
  31. allowPositionals: true,
  32. options: {
  33. skipLib: {
  34. type: 'boolean',
  35. short: 'l',
  36. },
  37. skipApp: {
  38. type: 'boolean',
  39. short: 'a',
  40. },
  41. skipBench: {
  42. type: 'boolean',
  43. short: 'b',
  44. },
  45. noVapor: {
  46. type: 'boolean',
  47. },
  48. vdom: {
  49. type: 'boolean',
  50. short: 'v',
  51. },
  52. port: {
  53. type: 'string',
  54. short: 'p',
  55. default: '8193',
  56. },
  57. count: {
  58. type: 'string',
  59. short: 'c',
  60. default: '30',
  61. },
  62. warmupCount: {
  63. type: 'string',
  64. short: 'w',
  65. default: '5',
  66. },
  67. noHeadless: {
  68. type: 'boolean',
  69. },
  70. noMinify: {
  71. type: 'boolean',
  72. },
  73. reference: {
  74. type: 'boolean',
  75. short: 'r',
  76. },
  77. },
  78. })
  79. const port = +(/** @type {string}*/ (portStr))
  80. const count = +(/** @type {string}*/ (countStr))
  81. const warmupCount = +(/** @type {string}*/ (warmupCountStr))
  82. const sha = await getSha(true)
  83. if (!skipLib && !reference) {
  84. await buildLib()
  85. }
  86. if (!skipApp && !reference) {
  87. await rm('client/dist', { recursive: true }).catch(() => {})
  88. vdom && (await buildApp(false))
  89. !noVapor && (await buildApp(true))
  90. }
  91. const server = startServer()
  92. if (!skipBench) {
  93. await benchmark()
  94. server.close()
  95. }
  96. async function buildLib() {
  97. console.info(colors.blue('Building lib...'))
  98. /** @type {import('node:child_process').SpawnOptions} */
  99. const options = {
  100. cwd: path.resolve(import.meta.dirname, '../..'),
  101. stdio: 'inherit',
  102. env: { ...process.env, BENCHMARK: 'true' },
  103. }
  104. const [{ ok }, { ok: ok2 }, { ok: ok3 }] = await Promise.all([
  105. exec(
  106. 'pnpm',
  107. `run --silent build shared compiler-core compiler-dom -pf cjs`.split(' '),
  108. options,
  109. ),
  110. exec(
  111. 'pnpm',
  112. 'run --silent build compiler-sfc compiler-ssr compiler-vapor -f cjs'.split(
  113. ' ',
  114. ),
  115. options,
  116. ),
  117. exec(
  118. 'pnpm',
  119. `run --silent build shared reactivity runtime-core runtime-dom runtime-vapor vue -f esm-bundler+esm-bundler-runtime`.split(
  120. ' ',
  121. ),
  122. options,
  123. ),
  124. ])
  125. if (!ok || !ok2 || !ok3) {
  126. console.error('Failed to build')
  127. process.exit(1)
  128. }
  129. }
  130. /** @param {boolean} isVapor */
  131. async function buildApp(isVapor) {
  132. console.info(
  133. colors.blue(`\nBuilding ${isVapor ? 'Vapor' : 'Virtual DOM'} app...\n`),
  134. )
  135. process.env.NODE_ENV = 'production'
  136. const CompilerSFC =
  137. await import('../../packages/compiler-sfc/dist/compiler-sfc.cjs.js')
  138. const runtimePath = path.resolve(
  139. import.meta.dirname,
  140. '../../packages/vue/dist/vue.runtime.esm-bundler.js',
  141. )
  142. const mode = isVapor ? 'vapor' : 'vdom'
  143. await build({
  144. root: './client',
  145. base: `/${mode}`,
  146. define: {
  147. 'import.meta.env.IS_VAPOR': String(isVapor),
  148. },
  149. build: {
  150. minify: !noMinify,
  151. outDir: path.resolve('./client/dist', mode),
  152. rolldownOptions: {
  153. onwarn(log, handler) {
  154. if (log.code === 'INVALID_ANNOTATION') return
  155. handler(log)
  156. },
  157. },
  158. },
  159. resolve: {
  160. alias: {
  161. vue: runtimePath,
  162. },
  163. },
  164. clearScreen: false,
  165. plugins: [
  166. Vue({
  167. compiler: CompilerSFC,
  168. }),
  169. ],
  170. })
  171. }
  172. function startServer() {
  173. const server = connect()
  174. .use(sirv(reference ? './reference' : './client/dist', { dev: true }))
  175. .listen(port)
  176. printPort()
  177. process.on('SIGTERM', () => server.close())
  178. return server
  179. }
  180. async function benchmark() {
  181. console.info(colors.blue(`\nStarting benchmark...`))
  182. const browser = await initBrowser()
  183. await mkdir('results', { recursive: true }).catch(() => {})
  184. if (!noVapor) {
  185. await doBench(browser, true)
  186. }
  187. if (vdom) {
  188. await doBench(browser, false)
  189. }
  190. await browser.close()
  191. }
  192. /**
  193. * @param {boolean} isVapor
  194. */
  195. function getURL(isVapor) {
  196. return `http://localhost:${port}/${reference ? '' : isVapor ? 'vapor' : 'vdom'}/`
  197. }
  198. /**
  199. *
  200. * @param {import('puppeteer').Browser} browser
  201. * @param {boolean} isVapor
  202. */
  203. async function doBench(browser, isVapor) {
  204. const mode = reference ? `reference` : isVapor ? 'vapor' : 'vdom'
  205. console.info('\n\nmode:', mode)
  206. const page = await browser.newPage()
  207. page.emulateCPUThrottling(4)
  208. await page.goto(getURL(isVapor), {
  209. waitUntil: 'networkidle0',
  210. })
  211. await forceGC()
  212. const t = performance.now()
  213. console.log('warmup run')
  214. await eachRun(() => withoutRecord(benchOnce), warmupCount)
  215. console.log('benchmark run')
  216. await eachRun(benchOnce, count)
  217. console.info(
  218. 'Total time:',
  219. colors.cyan(((performance.now() - t) / 1000).toFixed(2)),
  220. 's',
  221. )
  222. const times = await getTimes()
  223. const result =
  224. /** @type {Record<string, typeof compute>} */
  225. Object.fromEntries(Object.entries(times).map(([k, v]) => [k, compute(v)]))
  226. console.table(result)
  227. await writeFile(
  228. `results/benchmark-${sha}-${mode}.json`,
  229. JSON.stringify(result, undefined, 2),
  230. )
  231. await page.close()
  232. return result
  233. async function benchOnce() {
  234. await clickButton('run') // test: create rows
  235. await clickButton('update') // partial update
  236. await clickButton('swaprows') // swap rows
  237. await select() // test: select row, remove row
  238. await clickButton('clear') // clear rows
  239. await withoutRecord(() => clickButton('run'))
  240. await clickButton('add') // append rows to large table
  241. await withoutRecord(() => clickButton('clear'))
  242. await clickButton('runlots') // create many rows
  243. await withoutRecord(() => clickButton('clear'))
  244. // TODO replace all rows
  245. }
  246. function getTimes() {
  247. return page.evaluate(() => /** @type {any} */ (globalThis).times)
  248. }
  249. async function forceGC() {
  250. await page.evaluate(
  251. `window.gc({type:'major',execution:'sync',flavor:'last-resort'})`,
  252. )
  253. }
  254. /** @param {() => any} fn */
  255. async function withoutRecord(fn) {
  256. const currentRecordTime = await page.evaluate(() => globalThis.recordTime)
  257. await page.evaluate(() => (globalThis.recordTime = false))
  258. await fn()
  259. await page.evaluate(
  260. currentRecordTime => (globalThis.recordTime = currentRecordTime),
  261. currentRecordTime,
  262. )
  263. }
  264. /** @param {string} id */
  265. async function clickButton(id) {
  266. await page.click(`#${id}`)
  267. await wait()
  268. }
  269. async function select() {
  270. for (let i = 1; i <= 10; i++) {
  271. await page.click(`tbody > tr:nth-child(2) > td:nth-child(2) > a`)
  272. await page.waitForSelector(`tbody > tr:nth-child(2).danger`)
  273. await page.click(`tbody > tr:nth-child(2) > td:nth-child(3) > a`)
  274. await wait()
  275. }
  276. }
  277. async function wait() {
  278. await page.waitForSelector('.done')
  279. }
  280. }
  281. /**
  282. * @param {Function} bench
  283. * @param {number} count
  284. */
  285. async function eachRun(bench, count) {
  286. for (let i = 0; i < count; i++) {
  287. readline.cursorTo(process.stdout, 0)
  288. readline.clearLine(process.stdout, 0)
  289. process.stdout.write(`${i + 1}/${count}`)
  290. await bench()
  291. }
  292. if (count === 0) {
  293. process.stdout.write('0/0 (skip)')
  294. }
  295. process.stdout.write('\n')
  296. }
  297. async function initBrowser() {
  298. const disableFeatures = [
  299. 'Translate', // avoid translation popups
  300. 'PrivacySandboxSettings4', // avoid privacy popup
  301. 'IPH_SidePanelGenericMenuFeature', // bookmark popup see https://github.com/krausest/js-framework-benchmark/issues/1688
  302. ]
  303. const args = [
  304. '--js-flags=--expose-gc', // needed for gc() function
  305. '--no-default-browser-check',
  306. '--disable-sync',
  307. '--no-first-run',
  308. '--ash-no-nudges',
  309. '--disable-extensions',
  310. `--disable-features=${disableFeatures.join(',')}`,
  311. ]
  312. const headless = !noHeadless
  313. console.info('headless:', headless)
  314. const browser = await launch({
  315. headless: headless,
  316. args,
  317. })
  318. console.log('browser version:', colors.blue(await browser.version()))
  319. return browser
  320. }
  321. /** @param {number[]} array */
  322. function compute(array) {
  323. const n = array.length
  324. const max = Math.max(...array)
  325. const min = Math.min(...array)
  326. const mean = array.reduce((a, b) => a + b) / n
  327. const std = Math.sqrt(
  328. array.map(x => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n,
  329. )
  330. const median = array.slice().sort((a, b) => a - b)[Math.floor(n / 2)]
  331. return {
  332. max: round(max),
  333. min: round(min),
  334. mean: round(mean),
  335. std: round(std),
  336. median: round(median),
  337. }
  338. }
  339. /** @param {number} n */
  340. function round(n) {
  341. return +n.toFixed(2)
  342. }
  343. function printPort() {
  344. const vaporLink = !noVapor
  345. ? `\n${reference ? `Reference` : `Vapor`}: ${colors.blue(getURL(true))}`
  346. : ''
  347. const vdomLink = vdom ? `\nvDom: ${colors.blue(getURL(false))}` : ''
  348. console.info(`\n\nServer started at`, vaporLink, vdomLink)
  349. }