Skip to content

Instantly share code, notes, and snippets.

@leipreachan
Last active February 17, 2025 09:29
Show Gist options
  • Save leipreachan/0af29a8f5c25eab8dd28fd741966d39b to your computer and use it in GitHub Desktop.
Save leipreachan/0af29a8f5c25eab8dd28fd741966d39b to your computer and use it in GitHub Desktop.
different solutions to check for duplicates
const hasDuplicateOneline = (array) =>
new Set(array).size != array.length;
const hasDuplicateAlternative = (arr) =>
arr.some((value, index, origin) => origin.indexOf(value) !== index);
let z = [];
for (let i = 0; i < 10_000; i++) {
z.push(i);
}
// z.push(1);
const testFunctions = [hasDuplicateOneline, hasDuplicateAlternative];
let start, stop, avg, execTime = {};
for (let index in testFunctions) {
const func = testFunctions[index];
execTime[func.name] = [];
for (let j=0; j<1000; j++) {
performance.mark('start');
testFunctions[index](z);
performance.mark('stop');
performance.measure('executionTime', 'start', 'stop');
execTime[func.name].push(performance.getEntriesByName('executionTime')[0].duration);
}
performance.clearMarks();
performance.clearMeasures();
}
console.log(`${z.length} elements:`);
for (let index in testFunctions) {
const func = testFunctions[index];
avg = execTime[func.name].reduce((prev, cur) => {return prev + cur}, 0) / execTime[func.name].length;
console.log(`${func.name} ${execTime[func.name].length} runs avg: ${avg}`);
}
@leipreachan
Copy link
Author

$ bun simple.js
10001 elements:
hasDuplicateOneline 100 runs avg: 0.24
hasDuplicateAlternative 100 runs avg: 15.73

@leipreachan
Copy link
Author

$ node simple.js
10001 elements:
hasDuplicateOneline 100 runs avg: 0.42
hasDuplicateAlternative 100 runs avg: 10.52
$ bun -version
1.2.2
laptop:~/workspace/tempproject 
$ node --version
v23.7.0

@guest271314
Copy link

Set has size property, not length. The current version

const hasDuplicateOneline = (array) => 
    new Set(array).length != array.length;

is evaluating undefined != array.length.

That is currently

hasDuplicateOneline([1,2,3]) // true

evaluates to true, which is incorrect.

Should be

var hasDuplicateOneline = (array) => 
    new Set(array).size != array.length;
hasDuplicateOneline([1,2,3]) // false

@leipreachan
Copy link
Author

Set has size property, not length. The current version

const hasDuplicateOneline = (array) => 
    new Set(array).length != array.length;

is evaluating undefined != array.length.

That is currently

hasDuplicateOneline([1,2,3]) // true

evaluates to true, which is incorrect.

Should be

var hasDuplicateOneline = (array) => 
    new Set(array).size != array.length;
hasDuplicateOneline([1,2,3]) // false

well pointed, I updated the code. Yet the difference is still noticeable

$ node simple.js
10000 elements:
hasDuplicateOneline 1000 runs avg: 0.6117080000000104
hasDuplicateAlternative 1000 runs avg: 10.793499999999812

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment