Created
April 27, 2023 15:45
-
-
Save RomanTurner/582b9437e79974030b1c8748a4889b08 to your computer and use it in GitHub Desktop.
Testing speed of lookups
This file contains hidden or 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
// // Generate a large sorted array of random integers | |
const arraySize = 1500; | |
const amountOfRecipes = 1000; | |
const sortedArray = Array.from({ length: arraySize }, (_, i) => i).sort( | |
(a, b) => a - b | |
); | |
const jsonArray = JSON.stringify(sortedArray); | |
function binarySearch(arr, val) { | |
let start = 0; | |
let end = arr.length - 1; | |
while (start <= end) { | |
const mid = Math.floor((start + end) / 2); | |
if (arr[mid] === val) { | |
return true; | |
} | |
if (val < arr[mid]) { | |
end = mid - 1; | |
} else { | |
start = mid + 1; | |
} | |
} | |
return false; | |
} | |
let targetValue = sortedArray[Math.floor(Math.random() * arraySize)]; | |
// Measure the execution time of binary search | |
console.group(); | |
console.time("binary search"); | |
console.time("Binary Parsing"); | |
const arrayFromJson = JSON.parse(jsonArray); | |
console.timeEnd("Binary Parsing"); | |
for (let i = 0; i < amountOfRecipes; ++i) { | |
binarySearch(arrayFromJson, targetValue); | |
targetValue = sortedArray[Math.floor(Math.random() * arraySize)]; | |
} | |
console.timeEnd("binary search"); | |
console.groupEnd(); | |
// Measure the execution time of Array.prototype.includes() | |
console.group(); | |
console.time("Array.prototype.includes()"); | |
console.time("Includes Parsing"); | |
const arrayFromJson2 = JSON.parse(jsonArray); | |
console.timeEnd("Includes Parsing"); | |
for (let i = 0; i < amountOfRecipes; ++i) { | |
arrayFromJson2.includes(targetValue); | |
targetValue = sortedArray[Math.floor(Math.random() * arraySize)]; | |
} | |
console.timeEnd("Array.prototype.includes()"); | |
console.groupEnd(); | |
// Measure the execution time of Set.has() | |
console.group(); | |
console.time("Set.has()"); | |
console.time("Set Parsing"); | |
const mySet = new Set(JSON.parse(jsonArray)); | |
console.timeEnd("Set Parsing"); | |
for (let i = 0; i < amountOfRecipes; ++i) { | |
mySet.has(targetValue); | |
targetValue = sortedArray[Math.floor(Math.random() * arraySize)]; | |
} | |
console.timeEnd("Set.has()"); | |
console.groupEnd(); | |
// Measure the execution time of POJO | |
console.group(); | |
console.time("POJO[]"); | |
console.time("POJO Parsing"); | |
const mySet = new Set(JSON.parse(jsonArray)); | |
console.timeEnd("POJO Parsing"); | |
for (let i = 0; i < amountOfRecipes; ++i) { | |
mySet.has(targetValue); | |
targetValue = sortedArray[Math.floor(Math.random() * arraySize)]; | |
} | |
console.timeEnd("POJO[]"); | |
console.groupEnd(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment