index.js 8.5 KB

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