window.cachedFormatter = new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' });
window.cachedFormatter.format(3_950_219.56);
new Intl.NumberFormat('pt-BR', { style: 'currency', currency: 'BRL' }).format(3_950_219.56);
(3_950_219.56).toLocaleString('pt-BR', { style: 'currency', currency: 'BRL' });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
cached Intl.NumberFormat instance | |
new Intl.NumberFormat | |
Number.prototype.toLocaleString |
Test name | Executions per second |
---|---|
cached Intl.NumberFormat instance | 1148843.9 Ops/sec |
new Intl.NumberFormat | 28192.9 Ops/sec |
Number.prototype.toLocaleString | 29502.8 Ops/sec |
What is being tested?
MeasureThat.net is testing the performance of three different approaches to format currency values:
Intl.NumberFormat
instance: This approach creates an instance of Intl.NumberFormat
with a specific locale and options, caches it in the window.cachedFormatter
variable, and then uses this cached instance to format a currency value.Intl.NumberFormat
instance: This approach creates a new instance of Intl.NumberFormat
with the same locale and options as the first approach, but without caching it.Number.prototype.toLocaleString
method: This approach uses the toLocaleString
method on the Number
prototype to format the currency value.Options compared
The three approaches differ in how they create and use the formatting instance:
Number.prototype.toLocaleString
method is a built-in method that formats numbers in a specific locale, but its performance may vary depending on the browser implementation.Pros and Cons
Here's a brief summary of the pros and cons of each approach:
Number.prototype.toLocaleString
method: Pros:Libraries and features
None of the approaches rely on external libraries, but they do use some JavaScript features:
Intl.NumberFormat
is used in both cached and newly created instance approaches. It's a part of the ECMAScript Internationalization API (ES6) and provides a way to format numbers with locale-specific options.toLocaleString
method on Number.prototype
is also part of the ES6 API, but its implementation may vary depending on the browser.Special JS features
None of the approaches use special JavaScript features that are not widely supported. However, they do rely on some built-in methods and properties, such as Intl.NumberFormat
and Number.prototype.toLocaleString
.
I hope this explanation helps!