Promise.all

Benchmark created on


Setup

const rawParams = {
  country_code: 'US',
  city: 'New York',
  postal_code: '10001',
  region_code: 'NY',
  other_key: 'Some Value',
  null_key: null
};

function hashString({ rawString, algorithm }) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(`${algorithm}_${rawString}`), Math.random() * 100);
  });
}

async function processParamsWithPromiseAll(params) {
  return Promise.all(
    Object.entries(params).map(async ([key, value]) => {
      if (key === 'country_code' && typeof value === 'string') {
        return ['country', await hashString({ rawString: value.trim().toLowerCase(), algorithm: 'sha256' })];
      }
      if (key === 'city' && typeof value === 'string') {
        return ['ct', await hashString({ rawString: value.trim().toLowerCase().replace(/\s+/g, ''), algorithm: 'sha256' })];
      }
      if (key === 'postal_code' && typeof value === 'string') {
        return ['zp', await hashString({ rawString: value.trim().toLowerCase(), algorithm: 'sha256' })];
      }
      if (key === 'region_code' && typeof value === 'string') {
        return ['st', await hashString({ rawString: value.trim().toLowerCase().replace(/\s+/g, ''), algorithm: 'sha256' })];
      }
      if (value != null) return [key, value];
      return [key, null];
    })
  );
}

async function processParamsSequential(params) {
  const out = [];
  for (const [key, value] of Object.entries(params)) {
    if (key === 'country_code' && typeof value === 'string') {
      out.push(['country', await hashString({ rawString: value.trim().toLowerCase(), algorithm: 'sha256' })]);
    } else if (key === 'city' && typeof value === 'string') {
      out.push(['ct', await hashString({ rawString: value.trim().toLowerCase().replace(/\s+/g, ''), algorithm: 'sha256' })]);
    } else if (key === 'postal_code' && typeof value === 'string') {
      out.push(['zp', await hashString({ rawString: value.trim().toLowerCase(), algorithm: 'sha256' })]);
    } else if (key === 'region_code' && typeof value === 'string') {
      out.push(['st', await hashString({ rawString: value.trim().toLowerCase().replace(/\s+/g, ''), algorithm: 'sha256' })]);
    } else if (value != null) {
      out.push([key, value]);
    } else {
      out.push([key, null]);
    }
  }
  return out;
}

Test runner

Ready to run.

Testing in
TestOps/sec
Promise.all
processParamsWithPromiseAll(rawParams).then(() => deferred.resolve());

ready
No Promise.all
processParamsSequential(rawParams).then(() => deferred.resolve());

ready

Revisions

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