For fun, I decided to calculate how much faster a linked list is at removing the first item compared to an array (using array.shift()
). As it turns out, on average, when dealing with 10,000 items, a linked list is about 400% faster compared to an array.
Here is the example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://www.kirupa.com/js/linkedlist_v1.js"></script>
</head>
<body>
<script>
let myList = new LinkedList();
let start, end;
for (let i = 0; i < 10000; i++) {
let num = Math.round(Math.random() * 10000);
myList.addFirst(num);
}
start = performance.now();
for (let i = 0; i < 10000; i++) {
myList.removeFirst();
}
end = performance.now();
console.log("Elapsed time for linkedlist is: " + (end - start));
let myArray = [];
for (let i = 0; i < 10000; i++) {
let num = Math.round(Math.random() * 10000);
myArray.push(num)
}
start = performance.now();
for (let i = 0; i < 10000; i++) {
myArray.shift();
}
end = performance.now();
console.log("Elapsed time for arrays is: " + (end - start));
</script>
</body>
</html>