Skip to content

Commit df3c27f

Browse files
committed
chore: add a benchmark comparing the performance of functions created with the expression parser with native JS functions
1 parent 4d08f7f commit df3c27f

2 files changed

Lines changed: 33 additions & 2 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// test performance of plain JS functions vs custom functions defined via the expression parser
2+
3+
import assert from 'node:assert'
4+
import { Bench } from 'tinybench'
5+
import { all, create } from '../../lib/esm/index.js'
6+
import { formatTaskResult } from './utils/formatTaskResult.js'
7+
8+
const math = create(all)
9+
10+
const cubeJsPlain = (x) => x * x * x
11+
const cubeJsWithMathjs = (x) => math.multiply(x, math.multiply(x, x))
12+
const cubeMathjsExpr = math.evaluate('f(x) = x * x * x')
13+
14+
assert.strictEqual(cubeJsPlain(3), 27)
15+
assert.strictEqual(cubeJsWithMathjs(3), 27)
16+
assert.strictEqual(cubeMathjsExpr(3), 27)
17+
18+
const bench = new Bench({ time: 100, iterations: 1000 })
19+
.add('cubeJsPlain', function () {
20+
cubeJsPlain(3)
21+
})
22+
.add('cubeJsWithMathjs', function () {
23+
cubeJsWithMathjs(3)
24+
})
25+
.add('cubeMathjsExpr', function () {
26+
cubeMathjsExpr(3)
27+
})
28+
29+
bench.addEventListener('cycle', (event) => console.log(formatTaskResult(bench, event.task, 3)))
30+
await bench.run()

test/benchmark/utils/formatTaskResult.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,16 @@ const varianceWidth = 8
55
* Format a result like "Task name 2.30 µs ±0.79%"
66
* @param {import('tinybench').Bench} bench
77
* @param {import('tinybench').Task} task
8+
* @param {number} [digits]
89
* @return {string}
910
*/
10-
export function formatTaskResult (bench, task) {
11+
export function formatTaskResult (bench, task, digits = 2) {
1112
const nameWidth = Math.max(...bench.tasks.map(task => task.name.length)) + 1
1213

1314
const name = task.name
1415
const { variance, mean } = task.result.latency
1516

16-
const meanStr = `${(mean * 1000).toFixed(2)} \u00b5s`
17+
const meanStr = `${(mean * 1000).toFixed(digits)} \u00b5s`
1718
const varianceStr = ${((variance / mean) * 100).toFixed(2)}%`
1819
return `${padRight(name, nameWidth)} ${padLeft(meanStr, durationWidth)} ${padLeft(varianceStr, varianceWidth)}`
1920
}

0 commit comments

Comments
 (0)