Skip to content

Instantly share code, notes, and snippets.

@Cadienvan
Last active February 11, 2023 10:32
Show Gist options
  • Save Cadienvan/404465a7885e6eabc9261061c6f3f3c7 to your computer and use it in GitHub Desktop.
Save Cadienvan/404465a7885e6eabc9261061c6f3f3c7 to your computer and use it in GitHub Desktop.
Tests about inverted index performances on JS arrays
const linearArray = [];
const testArray = {
// The array that will hold the values
array: [],
// The inverted index
index: {},
// The push function
push: function (value) {
// Push the value to the array
this.array.push(value);
// Save the inverted index
this.index[value] = this.array.length - 1;
},
findIndex: function (value) {
// Return the value at the inverted index
return this.index[value];
},
};
let start, end;
// Fill the array with 1 milion random numbers
start = Date.now();
for (let i = 0; i < 100000; i++) {
linearArray.push(Math.random());
}
end = Date.now();
console.log(`[LINEAR] Time taken to fill: ${end - start}ms`);
// Fill the testArray with the same values as the linearArray
start = Date.now();
for (let i = 0; i < linearArray.length; i++) {
testArray.push(linearArray[i]);
}
end = Date.now();
console.log(`[TESTER] Time taken to fill: ${end - start}ms`);
// Testing findIndex in the test array
start = Date.now();
for (let i = 0; i < linearArray.length; i++) {
// Find the index at the same index in the linearArray
testArray.findIndex(linearArray[i]);
}
end = Date.now();
console.log(`[TESTER] Time taken to findIndex: ${end - start}ms`);
// Testing findIndex in the linear array
start = Date.now();
for (let i = 0; i < linearArray.length; i++) {
// Find the index at the same index in the linearArray
linearArray.findIndex((value) => value === linearArray[i]);
}
end = Date.now();
console.log(`[LINEAR] Time taken to findIndex: ${end - start}ms`);
@Cadienvan
Copy link
Author

[LINEAR] Time taken to fill: 45ms
[TESTER] Time taken to fill: 74ms
[TESTER] Time taken to findIndex: 50ms
[LINEAR] Time taken to findIndex: 7147ms

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