|
| 1 | +import { describe, test } from "vitest"; |
| 2 | +import { |
| 3 | + iterativeFibonacci as iterativeFibonacciExport, |
| 4 | + recursiveFibonacci as recursiveFibonacciExport, |
| 5 | +} from "./fibonacci"; |
| 6 | + |
| 7 | +// Read the imported bindings once: Vite's module runner exposes exports through |
| 8 | +// getters, and reading one inside the measured loop adds overhead to every |
| 9 | +// iteration (Vitest warns about it). |
| 10 | +const recursiveFibonacci = recursiveFibonacciExport; |
| 11 | +const iterativeFibonacci = iterativeFibonacciExport; |
| 12 | + |
| 13 | +// Vitest 5 declares benchmarks through the `bench` test-context fixture: each |
| 14 | +// `bench()` returns a registration that runs on `.run()`, or as part of a |
| 15 | +// `bench.compare()` group. |
| 16 | +describe("fibonacci", () => { |
| 17 | + test("fibo 15", async ({ bench }) => { |
| 18 | + await bench.compare( |
| 19 | + bench("recursive", () => { |
| 20 | + recursiveFibonacci(15); |
| 21 | + }), |
| 22 | + bench("iterative", () => { |
| 23 | + iterativeFibonacci(15); |
| 24 | + }), |
| 25 | + ); |
| 26 | + }); |
| 27 | + |
| 28 | + test("fibo 20", async ({ bench }) => { |
| 29 | + await bench.compare( |
| 30 | + bench("recursive", () => { |
| 31 | + recursiveFibonacci(20); |
| 32 | + }), |
| 33 | + bench("iterative", () => { |
| 34 | + iterativeFibonacci(20); |
| 35 | + }), |
| 36 | + ); |
| 37 | + }); |
| 38 | +}); |
0 commit comments