Last active
February 11, 2023 10:32
-
-
Save Cadienvan/404465a7885e6eabc9261061c6f3f3c7 to your computer and use it in GitHub Desktop.
Tests about inverted index performances on JS arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[LINEAR] Time taken to fill: 45ms
[TESTER] Time taken to fill: 74ms
[TESTER] Time taken to findIndex: 50ms
[LINEAR] Time taken to findIndex: 7147ms