Deterministic - reduce vs filter (v5)

Revision 5 of this benchmark created on


Description

Deterministic - reduce vs filter

Setup

/**
 * Creates a seeded pseudo-random number generator (PRNG).
 * It will always produce the same sequence of numbers for the same seed.
 * @param {number} seed - The starting number for the sequence.
 * @returns {function(): number} A function that returns the next random number between 0 and 1.
 */
function createSeededRandom(seed) {
  return function() {
    // mulberry32 algorithm
    var t = seed += 0x6D2B79F5;
    t = Math.imul(t ^ t >>> 15, t | 1);
    t ^= t + Math.imul(t ^ t >>> 7, t | 61);
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  }
}

// 1. Define a seed. The output will always be the same for this seed.
const seed = 12345;

// 2. Create the deterministic random function from the seed.
const seededRandom = createSeededRandom(seed);

// 3. Define the character and get its code (97) to use as a maximum value.
const char = 'a';
const charCode = char.charCodeAt(0);

// 4. Generate the deterministic number of 'a's to create (will be 64 with this seed).
const numberOfAs = Math.floor(seededRandom() * (charCode + 1));

// 5. Create the array of 'a's.
const prefixArray = Array(numberOfAs).fill(char);

// 6. Define the base array.
const baseArray = ["image/png", "image/jpeg", "image/gif", "image/tiff"];

// 7. Combine the arrays to get the final result.
const arr = [...prefixArray, ...baseArray];

Test runner

Ready to run.

Testing in
TestOps/sec
reduce
arr.reduce((acc, type) => {
	if (type.startsWith('a')) acc.push(type);
	return acc;
}, []);
ready
filter
arr.filter((type) => type.startsWith('a'))
ready

Revisions

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