How to Use Deno Bench for Benchmarking Code
Use
deno bench to run benchmark tests defined with Deno.bench() in your code. Write benchmark functions inside Deno.bench() and run deno bench in the terminal to see performance results.Syntax
The basic syntax to create a benchmark test in Deno is using Deno.bench(). Inside it, you provide a name and a function that contains the code you want to measure.
Deno.bench(name, fn): Defines a benchmark with a descriptivenameand a functionfnto run.- The function
fnshould contain the code you want to test repeatedly. - You run all benchmarks by executing
deno benchin your terminal.
typescript
Deno.bench("example benchmark", () => { // code to benchmark });
Example
This example shows how to benchmark a simple loop that sums numbers from 1 to 1000. Running deno bench will execute this benchmark and show how long it took.
typescript
Deno.bench("sum 1 to 1000", () => { let total = 0; for (let i = 1; i <= 1000; i++) { total += i; } });
Output
running 1 benchmark...
sum 1 to 1000: 1.23ms
1 benchmark finished
Common Pitfalls
Common mistakes when using deno bench include:
- Not wrapping the code to benchmark inside
Deno.bench(), so it won't run as a benchmark. - Including asynchronous code without marking the function
asyncor awaiting promises. - Running
deno benchwithout the necessary permissions if your benchmark accesses files or network.
typescript
/* Wrong: code outside Deno.bench, so no benchmark runs */ // let total = 0; // for (let i = 1; i <= 1000; i++) { // total += i; // } /* Right: code inside Deno.bench */ Deno.bench("correct benchmark", () => { let total = 0; for (let i = 1; i <= 1000; i++) { total += i; } });
Quick Reference
Summary tips for using deno bench:
- Define benchmarks with
Deno.bench(name, fn). - Use
asyncfunctions if benchmarking asynchronous code. - Run benchmarks with
deno benchin your terminal. - Use
--filterto run specific benchmarks by name. - Benchmarks run multiple iterations to measure average time.
Key Takeaways
Use Deno.bench() to define benchmark tests with a name and function.
Run benchmarks by executing deno bench in your terminal.
Wrap all code to measure inside the Deno.bench callback function.
Mark benchmark functions async if testing asynchronous code.
Use --filter option to run specific benchmarks by name.