Skip to content

Main content

JavaScript Benchmark Source Code

Browse the implementation files for JavaScript Benchmark.
tool.ts typescript
import { parseInteger } from '../../parse/integer/tool';

export const MAX_BENCHMARK_ITERATIONS = 1_000_000;

type Clock = () => number;
type BenchmarkRunner = () => unknown;

const createRunner = (
	initialization: string,
	code: string
): BenchmarkRunner | null => {
	try {
		const factory = new Function(
			`"use strict";\n${initialization}\nreturn () => {\n${code}\n};`
		);
		const runner = factory();
		return typeof runner === 'function' ? runner : null;
	} catch {
		return null;
	}
};

const runIterations = (
	runner: BenchmarkRunner,
	iterations: number
): void => {
	for (
		let iteration = 0;
		iteration < iterations;
		iteration += 1
	) {
		runner();
	}
};

const formatResult = (
	durationA: number,
	durationB: number,
	iterations: number
): string => {
	const difference = Math.abs(durationA - durationB);
	const comparison =
		durationA === durationB
			? 'A and B finished in the same time'
			: durationA < durationB
				? `A is ${difference.toFixed(3)} ms faster than B`
				: `B is ${difference.toFixed(3)} ms faster than A`;

	return [
		comparison,
		`Time A: ${durationA.toFixed(3)} ms`,
		`Time B: ${durationB.toFixed(3)} ms`,
		`Iterations: ${iterations}`
	].join('\n');
};

export const benchmarkJavaScript = (
	initializationInput: unknown,
	codeAInput: unknown,
	codeBInput: unknown,
	iterationsInput: unknown,
	now: Clock = () => performance.now()
): string => {
	if (
		typeof initializationInput !== 'string' ||
		typeof codeAInput !== 'string' ||
		typeof codeBInput !== 'string' ||
		codeAInput.trim() === '' ||
		codeBInput.trim() === ''
	) {
		return '';
	}

	const iterations = parseInteger(iterationsInput);
	if (
		iterations === null ||
		iterations < 1 ||
		iterations > MAX_BENCHMARK_ITERATIONS
	) {
		return '';
	}

	const runnerA = createRunner(initializationInput, codeAInput);
	const runnerB = createRunner(initializationInput, codeBInput);
	if (!runnerA || !runnerB) return '';

	try {
		const startA = now();
		runIterations(runnerA, iterations);
		const endA = now();
		const startB = now();
		runIterations(runnerB, iterations);
		const endB = now();
		const durationA = endA - startA;
		const durationB = endB - startB;

		if (
			!Number.isFinite(durationA) ||
			!Number.isFinite(durationB) ||
			durationA < 0 ||
			durationB < 0
		) {
			return '';
		}

		return formatResult(durationA, durationB, iterations);
	} catch {
		return '';
	}
};

export const simpleBench = benchmarkJavaScript;

export const Tool: TypeTool = {
	name: 'JavaScript Benchmark',
	slug: 'benchmark/javascript',
	intro:
		'Compare how long two JavaScript snippets take to run locally in your browser over the same number of iterations.',
	tool: benchmarkJavaScript,
	i: [
		{
			example: 'let value = 42;',
			help: 'Optional setup that runs once for each snippet. Only run code you trust.',
			label: 'Setup Code',
			placeholder: 'Declare values used by both snippets...',
			render: 'textarea',
			type: 'text'
		},
		{
			example: 'value += 1;',
			help: 'This snippet runs once per iteration.',
			label: 'JavaScript A',
			placeholder: 'Enter the first JavaScript snippet...',
			render: 'textarea',
			type: 'text'
		},
		{
			example: 'value = value + 1;',
			help: 'This snippet runs once per iteration.',
			label: 'JavaScript B',
			placeholder: 'Enter the second JavaScript snippet...',
			render: 'textarea',
			type: 'text'
		},
		{
			example: '10000',
			help: `Enter a whole number from 1 to ${MAX_BENCHMARK_ITERATIONS.toLocaleString(
				'en-US'
			)}.`,
			label: 'Iterations',
			placeholder: 'Number of iterations',
			type: 'number'
		}
	],
	o: [
		{
			example:
				'A is 0.125 ms faster than B\nTime A: 1.250 ms\nTime B: 1.375 ms\nIterations: 10000',
			label: 'Benchmark Result',
			placeholder: 'Benchmark timing will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	alternative: [
		{
			title: 'Big O Predictor',
			url: '/predict-big-o'
		}
	],
	cite: [
		{
			title: 'Benchmark - Wikipedia',
			url: 'https://en.wikipedia.org/wiki/Benchmark_(computing)'
		},
		{
			title: 'Performance.now() - MDN',
			url: 'https://developer.mozilla.org/en-US/docs/Web/API/Performance/now'
		}
	]
};

export default Tool;

Description

Browse the implementation files for JavaScript Benchmark.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools