Caching Intl.DateTimeFormat

Benchmark created on


Description

Testing the difference between creating an instance of Intl.DateTimeFormat each time or caching the instance but either deriving the key using JSON.stringify or manually making they key.

Setup

function extractDateParts(formatter, date, options){
  const dateParts = formatter.formatToParts(date);
  const configuredDatePartTypes = Object.keys(options);
  return dateParts.reduce(
    (acc, datePart) => {
      if (configuredDatePartTypes.includes(datePart.type)) {
        acc[datePart.type] = datePart.value;
      }
      return acc;
    },
    {
      day: '',
      month: '',
      year: '',
      weekday: ''
    }
  );	
}

const formattersJson = {};
const formattersManual = {};
const formattersManualMap = {};
const formattersManualReducer = {};

const locale = 'fr-FR';
const options = {
  day: 'numeric',
  month: 'long',
  year: '2-digit',
  weekday: 'long'
};
const optionKeys = Object.keys(options);

Test runner

Ready to run.

Testing in
TestOps/sec
No cache
extractDateParts(
	new Intl.DateTimeFormat(locale, options),
          new Date('2022-05-01'),
          options
        );
ready
With cache using JSON.stringify
const key = locale + JSON.stringify(options);
 
if(!(key in formattersJson)){
 	formattersJson[key] = new Intl.DateTimeFormat(locale, options);
 }
 
extractDateParts(formattersJson[key], new Date('2022-05-01'), options);

ready
With manual cache key
const key = locale + `day: ${options.day}, month: ${options.month}, year: ${options.year}, weekday: ${options.weekday}`;
 
if(!(key in formattersManual)){
 	formattersManual[key] = new Intl.DateTimeFormat(locale, options);
 }
 
extractDateParts(formattersManual[key], new Date('2022-05-01'), options);
ready
With manual cache key using an array with map/join
const key = locale + optionKeys.map((key) => key + options[key]).join(', ');
 
if(!(key in formattersManualMap)){
 	formattersManualMap[key] = new Intl.DateTimeFormat(locale, options);
 }
 
extractDateParts(formattersManualMap[key], new Date('2022-05-01'), options);
ready
With manual cache key using an array with reducer
const key = locale + optionKeys.reduce((allKeys, key) => allKeys + key + options[key] + ', ', '');
 
if(!(key in formattersManualReducer)){
 	formattersManualReducer[key] = new Intl.DateTimeFormat(locale, options);
 }
 
extractDateParts(formattersManualReducer[key], new Date('2022-05-01'), options);
ready

Revisions

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