Skip to content
jshacks.dev
Performance

Reuse Intl formatters in loops

Create one Intl.NumberFormat outside the loop and call its format method many times, instead of making a new formatter for every row you display.

1 min read
Summarize in AI

toLocaleString is convenient, but with locale options it may build a formatter on each call. For a table of thousands of rows, build the formatter once.

format.jsJavaScript
const prices = [1234.5, 99, 1_000_000];

// Creates a formatter every time.
const slow = prices.map((p) => p.toLocaleString('en-US', { style: 'currency', currency: 'USD' }));

// Creates it once and reuses it.
const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });
const fast = prices.map((p) => usd.format(p));

console.log(slow);
console.log(fast);
Text
[ '$1,234.50', '$99.00', '$1,000,000.00' ]
[ '$1,234.50', '$99.00', '$1,000,000.00' ]

Both produce the same strings. Creating an Intl formatter loads locale data and resolves the options, which is far more work than formatting a single number, so the saving grows with the row count.

Engines may cache part of the work inside toLocaleString, so measure with your real data before changing working code. The same advice holds for Intl.DateTimeFormat, Intl.PluralRules and Intl.Collator; for sorting, pass collator.compare to sort rather than localeCompare with options. See Intl.NumberFormat.

Taggedintl
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Performance

Time code with performance.now

Time a block of code with performance.now, which returns a monotonic high-resolution timestamp in milliseconds, and avoid the clock jumps Date.now can have.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.