index.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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: '30',
  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. page.emulateCPUThrottling(4)
  202. await page.goto(`http://localhost:${port}/${mode}`, {
  203. waitUntil: 'networkidle0',
  204. })
  205. await forceGC()
  206. const t = performance.now()
  207. for (let i = 0; i < count; i++) {
  208. await clickButton('run') // test: create rows
  209. await clickButton('update') // partial update
  210. await clickButton('swaprows') // swap rows
  211. await select() // test: select row, remove row
  212. await clickButton('clear') // clear rows
  213. await withoutRecord(() => clickButton('run'))
  214. await clickButton('add') // append rows to large table
  215. await withoutRecord(() => clickButton('clear'))
  216. await clickButton('runLots') // create many rows
  217. await withoutRecord(() => clickButton('clear'))
  218. // TODO replace all rows
  219. }
  220. console.info(
  221. 'Total time:',
  222. colors.cyan(((performance.now() - t) / 1000).toFixed(2)),
  223. 's',
  224. )
  225. const times = await getTimes()
  226. const result =
  227. /** @type {Record<string, typeof compute>} */
  228. Object.fromEntries(Object.entries(times).map(([k, v]) => [k, compute(v)]))
  229. console.table(result)
  230. await writeFile(
  231. `results/benchmark-${sha}-${mode}.json`,
  232. JSON.stringify(result, undefined, 2),
  233. )
  234. await page.close()
  235. return result
  236. function getTimes() {
  237. return page.evaluate(() => /** @type {any} */ (globalThis).times)
  238. }
  239. async function forceGC() {
  240. await page.evaluate(
  241. `window.gc({type:'major',execution:'sync',flavor:'last-resort'})`,
  242. )
  243. }
  244. /** @param {() => any} fn */
  245. async function withoutRecord(fn) {
  246. await page.evaluate(() => (globalThis.recordTime = false))
  247. await fn()
  248. await page.evaluate(() => (globalThis.recordTime = true))
  249. }
  250. /** @param {string} id */
  251. async function clickButton(id) {
  252. await page.click(`#${id}`)
  253. await wait()
  254. }
  255. async function select() {
  256. for (let i = 1; i <= 10; i++) {
  257. await page.click(`tbody > tr:nth-child(2) > td:nth-child(2) > a`)
  258. await page.waitForSelector(`tbody > tr:nth-child(2).danger`)
  259. await page.click(`tbody > tr:nth-child(2) > td:nth-child(3) > button`)
  260. await wait()
  261. }
  262. }
  263. async function wait() {
  264. await page.waitForSelector('.done')
  265. }
  266. }
  267. async function initBrowser() {
  268. const disableFeatures = [
  269. 'Translate', // avoid translation popups
  270. 'PrivacySandboxSettings4', // avoid privacy popup
  271. 'IPH_SidePanelGenericMenuFeature', // bookmark popup see https://github.com/krausest/js-framework-benchmark/issues/1688
  272. ]
  273. const args = [
  274. '--js-flags=--expose-gc', // needed for gc() function
  275. '--no-default-browser-check',
  276. '--disable-sync',
  277. '--no-first-run',
  278. '--ash-no-nudges',
  279. '--disable-extensions',
  280. `--disable-features=${disableFeatures.join(',')}`,
  281. ]
  282. const headless = !noHeadless
  283. console.info('headless:', headless)
  284. const browser = await launch({
  285. headless: headless,
  286. args,
  287. })
  288. console.log('browser version:', colors.blue(await browser.version()))
  289. return browser
  290. }
  291. /** @param {number[]} array */
  292. function compute(array) {
  293. const n = array.length
  294. const max = Math.max(...array)
  295. const min = Math.min(...array)
  296. const mean = array.reduce((a, b) => a + b) / n
  297. const std = Math.sqrt(
  298. array.map(x => Math.pow(x - mean, 2)).reduce((a, b) => a + b) / n,
  299. )
  300. const median = array.slice().sort((a, b) => a - b)[Math.floor(n / 2)]
  301. return {
  302. max: round(max),
  303. min: round(min),
  304. mean: round(mean),
  305. std: round(std),
  306. median: round(median),
  307. }
  308. }
  309. /** @param {number} n */
  310. function round(n) {
  311. return +n.toFixed(2)
  312. }
  313. /** @param {number} port */
  314. function printPort(port) {
  315. const vaporLink = !noVapor
  316. ? `\nVapor: ${colors.blue(`http://localhost:${port}/vapor`)}`
  317. : ''
  318. const vdomLink = vdom
  319. ? `\nvDom: ${colors.blue(`http://localhost:${port}/vdom`)}`
  320. : ''
  321. console.info(`\n\nServer started at`, vaporLink, vdomLink)
  322. }