Huge Array filter performance (v9)

Revision 9 of this benchmark created on


Setup

const existingArraySize = 1
const searchedArraySize = 100

// Shuffle is not in std lib :(
function shuffleArray(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
    return array
}

// Used to verify that we have the correct result
function assertResult(result) {
	if (result.length !== searchedArraySize - existingArraySize) throw new Error(`${result.length} is invalid length! Expected: ${searchedArraySize - existingArraySize}`)
}

// Prepare alpha array with random order
var alpha = shuffleArray(new Array(searchedArraySize).fill(null).map((_,i) => 10000+i))
// Pick few random values from the array as existing array (we assume the existing array always have matches in the original)
var existingValues = shuffleArray([...alpha]).slice(0, existingArraySize)
// Create helper structures
var existing = new Set(existingValues)
var existingMap = new Map(existingValues.map(v => [v,true]))
var existingObject = Object.fromEntries(existingValues.map(v => [v, true]))

Test runner

Ready to run.

Testing in
TestOps/sec
Filter and has
var result = alpha.filter((i) => !existing.has(i))
assertResult(result)
ready
Loop and plain object
function filter()
{
    var match = []

    for (const i of alpha)
    {
        if (existingObject[i] === undefined) match.push(i)
    }

    return match
}

var result = filter();
assertResult(result)
ready
Loop and some
function filter()
{
    var match = []

    for (const i of alpha)
    {
        if (!existingValues.some(value => value === i)) match.push(i)
    }

    return match
}

var result = filter();
assertResult(result)
ready
Loop and Set.has
function filter()
{
    var match = []

    for (const value of alpha)
    {
        if (!existing.has(value)) match.push(value)
    }

    return match
}

var result = filter();
assertResult(result)
ready
Loop and Map.has
function filter()
{
    var match = []

    for (const value of alpha)
    {
        if (!existingMap.has(value)) match.push(value)
    }

    return match
}

var result = filter();
assertResult(result)
ready

Revisions

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