Reputation: 697
I was curious to see the speed differences between arrays and objects, so I set up a test for filling, accessing, and deleting 100,000 items from an array and object. Accessing and filling the array were about equal with a ~3ms difference. Deleting from the array, however, resulted in 604ms difference(10ms vs 614ms). Why is this? I thought objects and arrays were pretty much the same.
Demo: https://codecanister.com/Project/b9f8de7c/1/result/
Upvotes: 1
Views: 816
Reputation: 8922
You just perform different actions. "delete" will just set the array-position to undefined. While splice will totally remove it by performing a loop with arr[i] = arr[i+1] for all 10,000 items of your array. You do this for all 10.000 items. See also this question
Upvotes: 0
Reputation: 413966
When you do that .splice()
, all the subsequent array entries have to be reassigned. That is, every property name after the one spliced out must be changed. There's no good way to do that except a straight linear traversal of the properties; a data structure that made that operation fast would make other, more common operations slower.
So consider the array [1, 2, 3, 4]
. The value of property "0" is 1
. If you splice that entry out, then the runtime has to set property "0" to 2
, property "1" to 3
, and property "2" to 4
.
Upvotes: 3