Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

assert: improve partialDeepStrictEqual performance and add benchmark #56555

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions benchmark/assert/partial-deep-strict-equal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
'use strict';

const common = require('../common.js');
const assert = require('assert');

const bench = common.createBenchmark(main, {
n: [50],
size: [1e3],
datasetName: ['objects', 'sets', 'maps', 'arrayBuffers', 'dataViewArrayBuffers'],
});

function createObjects(length, depth = 0) {
return Array.from({ length }, () => ({
foo: 'yarp',
nope: {
bar: '123',
a: [1, 2, 3],
c: {},
b: !depth ? createObjects(2, depth + 1) : [],
},
}));
}

function createSets(length, depth = 0) {
return Array.from({ length }, () => new Set([
'yarp',
{
bar: '123',
a: [1, 2, 3],
c: {},
b: !depth ? createSets(2, depth + 1) : new Set(),
},
]));
}

function createMaps(length, depth = 0) {
return Array.from({ length }, () => new Map([
['foo', 'yarp'],
['nope', new Map([
['bar', '123'],
['a', [1, 2, 3]],
['c', {}],
['b', !depth ? createMaps(2, depth + 1) : new Map()],
])],
]));
}

function createArrayBuffers(length) {
return Array.from({ length }, (_, n) => {
return new ArrayBuffer(n);
});
}

function createDataViewArrayBuffers(length) {
return Array.from({ length }, (_, n) => {
return new DataView(new ArrayBuffer(n));
});
}

const datasetMappings = {
objects: createObjects,
sets: createSets,
maps: createMaps,
arrayBuffers: createArrayBuffers,
dataViewArrayBuffers: createDataViewArrayBuffers,
};

function getDatasets(datasetName, size) {
return {
actual: datasetMappings[datasetName](size),
expected: datasetMappings[datasetName](size),
};
}

function main({ size, n, datasetName }) {
const { actual, expected } = getDatasets(datasetName, size);

bench.start();
for (let i = 0; i < n; ++i) {
assert.partialDeepStrictEqual(actual, expected);
}
bench.end(n);
}
57 changes: 35 additions & 22 deletions lib/assert.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
const {
ArrayBufferIsView,
ArrayBufferPrototypeGetByteLength,
ArrayFrom,
ArrayIsArray,
ArrayPrototypeIndexOf,
ArrayPrototypeJoin,
Expand Down Expand Up @@ -395,12 +394,11 @@ function partiallyCompareMaps(actual, expected, comparedObjects) {
const expectedIterator = FunctionPrototypeCall(SafeMap.prototype[SymbolIterator], expected);

for (const { 0: key, 1: expectedValue } of expectedIterator) {
if (!MapPrototypeHas(actual, key)) {
const actualValue = MapPrototypeGet(actual, key);
if (actualValue === undefined && !MapPrototypeHas(actual, key)) {
return false;
}

const actualValue = MapPrototypeGet(actual, key);

if (!compareBranch(actualValue, expectedValue, comparedObjects)) {
return false;
}
Expand Down Expand Up @@ -476,23 +474,37 @@ function partiallyCompareArrayBuffersOrViews(actual, expected) {

function partiallyCompareSets(actual, expected, comparedObjects) {
if (SetPrototypeGetSize(expected) > SetPrototypeGetSize(actual)) {
return false; // `expected` can't be a subset if it has more elements
return false;
}

if (isDeepEqual === undefined) lazyLoadComparison();

const actualArray = ArrayFrom(FunctionPrototypeCall(SafeSet.prototype[SymbolIterator], actual));
const expectedIterator = FunctionPrototypeCall(SafeSet.prototype[SymbolIterator], expected);
const usedIndices = new SafeSet();
let actualSet;

for (const expectedItem of expectedIterator) {
let foundMatch = false;

expectedIteration: for (const expectedItem of expectedIterator) {
for (let actualIdx = 0; actualIdx < actualArray.length; actualIdx++) {
if (!usedIndices.has(actualIdx) && isDeepStrictEqual(actualArray[actualIdx], expectedItem)) {
usedIndices.add(actualIdx);
continue expectedIteration;
// Check for primitives first to avoid useless loops
if (isPrimitive(expectedItem)) {
if (actual.has(expectedItem)) {
foundMatch = true;
}
} else {
actualSet ??= new SafeSet(FunctionPrototypeCall(SafeSet.prototype[SymbolIterator], actual));

for (const actualItem of actualSet) {
if (isDeepStrictEqual(actualItem, expectedItem)) {
actualSet.delete(actualItem);
foundMatch = true;
break;
}
}
}
return false;

if (!foundMatch) {
return false;
}
}

return true;
Expand All @@ -518,13 +530,12 @@ function partiallyCompareArrays(actual, expected, comparedObjects) {

// Create a map to count occurrences of each element in the expected array
const expectedCounts = new SafeMap();
const safeExpected = new SafeArrayIterator(expected);

for (const expectedItem of safeExpected) {
// Check if the item is a zero or a -0, as these need to be handled separately
const expectedIterator = new SafeArrayIterator(expected);
for (const expectedItem of expectedIterator) {
if (expectedItem === 0) {
const zeroKey = getZeroKey(expectedItem);
expectedCounts.set(zeroKey, (expectedCounts.get(zeroKey)?.count || 0) + 1);
expectedCounts.set(zeroKey, (expectedCounts.get(zeroKey) ?? 0) + 1);
} else {
let found = false;
for (const { 0: key, 1: count } of expectedCounts) {
Expand All @@ -540,10 +551,8 @@ function partiallyCompareArrays(actual, expected, comparedObjects) {
}
}

const safeActual = new SafeArrayIterator(actual);

for (const actualItem of safeActual) {
// Check if the item is a zero or a -0, as these need to be handled separately
const actualIterator = new SafeArrayIterator(actual);
for (const actualItem of actualIterator) {
if (actualItem === 0) {
const zeroKey = getZeroKey(actualItem);

Expand Down Expand Up @@ -723,6 +732,10 @@ function compareExceptionKey(actual, expected, key, message, keys, fn) {
}
}

function isPrimitive(value) {
return typeof value !== 'object' || value === null;
}

function expectedException(actual, expected, message, fn) {
let generatedMessage = false;
let throwError = false;
Expand All @@ -741,7 +754,7 @@ function expectedException(actual, expected, message, fn) {
}
throwError = true;
// Handle primitives properly.
} else if (typeof actual !== 'object' || actual === null) {
} else if (isPrimitive(actual)) {
const err = new AssertionError({
actual,
expected,
Expand Down
Loading