There are many options when implementing a queue in JavaScript. One possible implementation is to use an Array, adding elements to the queue with Array.push and removing them from the queue with Array.shift. Another possible implementation is by using a Linked List and adding to the tail and removing from the head.
Through testing for Stacks implementations, I have determined that Array.push and Array.pop, no matter the size of the Array, are 3-5 times faster than adding or removing an element to a Linked List's tail. Therefore, in JavaScript, it doesn't make sense to use a Linked List to implement a stack. But I am wondering, in the case of a Queue, what is the difference in performance when removing an element from the front of the array using Array.shift vs removing an element from the front of a list?
Tests ran on Chrome v63, on Windows 10.
Collections of 50,000 elements or less
Array.shift is 38%-40% slower than the equivalent operation on a Linked List.
Collections of more than 50,000 elements
Array.shift is essentially 100% slower than the equivalent operation on a Linked List.
Conclusions and recommendations
Array.shift, even on small arrays, is slower than on a Linked List, but if all you have to do is a few add or remove operations here and there, the performance hit might not be significant enough to warrant implementing a Linked List. Go with the Array. On the other hand, if you have a collection of more than 50k elements or frequently add and remove a large amount of items, it might be worth implementing a Linked List.
It is interesting to see that V8 obviously applies some optimizations behind the scenes to make Array.shift faster, but that optimization seems to only be applied to Arrays of size 50,000 or less. Just look at this benchmark test, it's quite obvious: https://jsperf.com/likedlistvsarray/1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With