0
0
DenoHow-ToBeginner ยท 3 min read

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 descriptive name and a function fn to run.
  • The function fn should contain the code you want to test repeatedly.
  • You run all benchmarks by executing deno bench in 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 async or awaiting promises.
  • Running deno bench without 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 async functions if benchmarking asynchronous code.
  • Run benchmarks with deno bench in your terminal.
  • Use --filter to 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.