doNotOptimize(value): any
Stores value where the optimizing compiler cannot prove it is unused, so the
computation that produced it is not eliminated as dead code. Returning value
allows the call to wrap an expression.
import { bench, doNotOptimize } from 'node:bench'; bench('Math.sqrt', (b) => { const n = 1_000_000; b.start(); for (let i = 0; i < n; i++) { doNotOptimize(Math.sqrt(i)); } b.end(n); });
const { bench, doNotOptimize } = require('node:bench'); bench('Math.sqrt', (b) => { const n = 1_000_000; b.start(); for (let i = 0; i < n; i++) { doNotOptimize(Math.sqrt(i)); } b.end(n); });
The call adds a small, constant cost to every invocation, so it is best suited
to work that takes longer than a few nanoseconds per call. For cheaper
operations, accumulate results into a value that is passed to
doNotOptimize() once after the measured region.
doNotOptimize() only prevents the result from being discarded. It does not
prevent the compiler from hoisting loop-invariant work or folding constant
inputs; vary inputs between iterations when the work would otherwise be
invariant.
doNotOptimize() is intended to be called only from benchmark functions while
a runner is executing them. Non-number values are retained until the current
sample finishes, after which the runner releases them. When called outside a
benchmark function, the most recent non-number value remains reachable until
doNotOptimize() is called again.