index.js 9.0 KB

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