Skip to content

Instantly share code, notes, and snippets.

@ChukwuEmekaAjah
Created August 23, 2020 23:07
Show Gist options
  • Save ChukwuEmekaAjah/f892697a29b3dbeb06ec273b94c251d3 to your computer and use it in GitHub Desktop.
Save ChukwuEmekaAjah/f892697a29b3dbeb06ec273b94c251d3 to your computer and use it in GitHub Desktop.
Linear time data duplicate check temporary storage comparison between JavaScript arrays and objects. It appears using arrays as temporary storage would give you 2x faster performance when compared to using Object literals.
let numbers = [];
for(let i = 0; i < 100000; i++){
numbers.push(Math.round(Math.random()*100000))
}
function hashDuplicate(value){
console.time("hash duplicate")
let hashValues = {}
for(let i = 0; i < numbers.length; i++){
if(hashValues[i] == undefined){
hashValues[i] = 1;
} else{
return true;
}
}
console.timeEnd("hash duplicate")
return false;
}
function arrayDuplicate(value){
console.time("array duplicate")
let arrayValues = [];
for(let i = 0; i < numbers.length; i++){
if(arrayValues[i] == undefined){
arrayValues[i] = 1;
} else{
return true;
}
}
console.timeEnd("array duplicate")
return false;
}
console.log("hash about to start")
console.log("found a duplicate for", numbers[0], hashDuplicate(numbers[0]))
console.log("hash has ended")
console.log("array about to start");
console.log("found a duplicate for", numbers[0], arrayDuplicate(numbers[0]))
console.log("array has ended")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment