Number formatting (v2)

Revision 2 of this benchmark created on


Setup

const numbers = Array.from({length: 1000}, () => Math.random() * 100)

const locale = "DE-de"

function formatNumbers(getFormatter) {
	for (const number of numbers) {
		const formatterOptions = {
			style: "decimal",
  			minimumFractionDigits: 0,
			maximumFractionDigits: 2,
			useGrouping: false,
			signDisplay: "exceptZero"
		}
		const formatter = getFormatter(locale, formatterOptions)
		formatter.format(number)
	}
}

Test runner

Ready to run.

Testing in
TestOps/sec
new formatter each time
function getFormatter(locale, formatterOptions) {
	return new Intl.NumberFormat(locale, formatterOptions)
	formatter.format(value)
}

formatNumbers(getFormatter)
ready
cached formatter by json string
const locale = "DE-de"
const formatterMap = new Map()

function getFormatter(locale, options) {
	const stringOptions = JSON.stringify(options)
	const formatter = formatterMap.get(stringOptions) ?? new Intl.NumberFormat(locale, options)
	formatterMap.set(stringOptions, formatter)
	return formatter
}

formatNumbers(getFormatter)
ready
cached formatter by args list
const locale = "DE-de"
let lastArgs = []
let lastFormatter

function getFormatter(locale, options) {
	const args = [options.style, options.minimumFractionDigits, options.maximumFractionDigits, options.useGrouping, options.signDisplay]
	const useCached = lastArgs.every((arg, index) => arg === args[index])
	const formatter = useCached  && lastFormatter ? lastFormatter : new Intl.NumberFormat(locale, options)
	lastFormatter = formatter
	lastArgs = args
	return formatter
}

formatNumbers(getFormatter)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.