Arrays in JavaScript are very easy to modify by adding and removing items. It somewhat masks the fact that most languages array's are fixed-size, and require complex operations to resize. It seems that JavaScript makes it easy to write poorly performing array code. This leads to the question:
What performance (in terms of big O time complexity) can I expect from JavaScript implementations in regards to array performance?
I assume that all reasonable JavaScript implementations have at least the following big O's.
- Access - O(1)
- Appending - O(n)
- Prepending - O(n)
- Insertion - O(n)
- Deletion - O(n)
- Swapping - O(1)
JavaScript lets you pre-fill an array to a certain size, using new Array(length)
syntax. (Bonus question: Is creating an array in this manner O(1) or O(n)) This is more like a conventional array, and if used as a pre-sized array, can allow O(1) appending. If circular buffer logic is added, you can achieve O(1) prepending. If a dynamically expanding array is used, O(log n) will be the average case for both of those.
Can I expect better performance for some things than my assumptions here? I don't expect anything is outlined in any specifications, but in practice it could be that all major implementations use optimized arrays behind the scenes. Are there dynamically expanding arrays or some other performance boosting algorithms at work?
P.S.
The reason I'm wondering this is because I'm researching some sorting algorithms, most of which seem to assume appending and deleting are O(1) operations when describing their overall big O.
.length
but that's about it.) Arrays are really not much different from plain Object instances. – Pointy Jul 17 '12 at 0:02length
property and pre-allocating space are two completely different things. – Pointy Jul 17 '12 at 0:04array[5]
on anew Array(10)
is O(1)? – Kendall Frey Jul 17 '12 at 0:06