Tuesday, June 4, 2024
53
rated 0 times [  59] [ 6]  / answers: 1 / hits: 33011  / 14 Years ago, thu, march 3, 2011, 12:00:00

If I remove one element from an array using splice() like so:



arr.splice(i, 1);


Will this be O(n) in the worst case because it shifts all the elements after i? Or is it constant time, with some linked list magic underneath?


More From » google-chrome

 Answers
24

Worst case should be O(n) (copying all n-1 elements to new array).



A linked list would be O(1) for a single deletion.



For those interested I've made this lazily-crafted benchmark. (Please don't run on Windows XP/Vista). As you can see from this though, it looks fairly constant (i.e. O(1)), so who knows what they're doing behind the scenes to make this crazy-fast. Note that regardless, the actual splice is VERY fast.



Rerunning an extended benchmark directly in the V8 shell that suggest O(n). Note though that you need huge array sizes to get a runtime that's likely to affect your code. This should be expected as if you look at the V8 code it uses memmove to create the new array.


[#93483] Wednesday, March 2, 2011, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
francokeganr

Total Points: 438
Total Questions: 102
Total Answers: 124

Location: Belarus
Member since Sat, Jul 18, 2020
4 Years ago
;