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.
-
1Function calls are expensive! There is a big difference between using the `delete` keyword and `.splice` function. – Ram Jul 12 '16 at 00:51
-
You should never use Date for time measurement. Use `performance.now();` instead. – Mick Jul 12 '16 at 00:51
-
Updated it, still about 600 ms difference. – jlynch630 Jul 12 '16 at 00:53
-
Another point: `delete` may cause deoptimisations (like dropping hidden classes in v8). – zerkms Jul 12 '16 at 01:03
-
1*Why is this?* You are asking for implementation details when the specification explicitly doesn't provide any. ECMA-262 provides a [*general delete algorithm*](http://www.ecma-international.org/ecma-262/6.0/#sec-delete-operator) for all Objects, so if Arrays and plain Objects differ, that is up to the implementation which might have optimisations for other, more common operations (e.g. an index for property lookup) that affect the performance of *delete*. – RobG Jul 12 '16 at 01:05
2 Answers
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
.

- 405,095
- 59
- 585
- 614
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
-
-
1""delete" will just set the array-position to undefined" --- it does not, it creates a hole in an array. – zerkms Jul 12 '16 at 01:03
-
It is different that just setting undefined because the position is ignored by foreach and map function. – bormat Nov 17 '16 at 00:01