JavaScript · Senior · Question 43 of 75
Why cache Intl.NumberFormat instances?
- ✓Correct answer: Creating a formatter is expensive, while calling it is cheap
- 2Without a cache the formatter returns different results for the same data
- 3A formatter for each locale can be created only once per session
Explanation
Intl constructors load locale data and parse options. Calling toLocaleString() in a loop over thousands of rows creates a formatter every time. Better to create new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }) once and call format.