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.

Answer from Andrew Marshall on Stack Overflow
Top answer
1 of 4
37

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.

2 of 4
7

¡Hi!

I did an experiment myself and would like to share my findings. The experiment was very simple, we ran 100 splice operations on an array of size n, and calculate the average time each splice function took. Then we varied the size of n, to check how it behave.

This graph summarizes our findings for big numbers:

For big numbers it seems to behave linearly.

We also checked with "small" numbers (they were still quite big but not as big):

On this case it seems to be constant.

If I would have to decide for one option I would say it is O(n), because that is how it behaves for big numbers. Bear in mind though, that the linear behaviour only shows for VERY big numbers.

However, It is hard to go for a definitive answer because the array implementation in javascript dependes A LOT on how the array is declared and manipulated.

I recommend this stackoverflow discussion and this quora discussion to understand how arrays work.

I run it in node v10.15.3 and the code used is the following:

const f = async () => {
  const n = 80000000;
  const tries = 100;
  const array = [];
  for (let i = 0; i < n; i++) { // build initial array
    array.push(i);
  }
  
  let sum = 0;
  for (let i = 0; i < tries; i++) {
    const index = Math.floor(Math.random() * (n));
    const start = new Date();
    array.splice(index, 1); // UNCOMMENT FOR OPTION A
    // array.splice(index, 0, -1); // UNCOMMENT FOR OPTION B
    const time = new Date().getTime() - start.getTime();
    sum += time;
    array.push(-2); // UNCOMMENT FOR OPTION A, to keep it of size n
    // array.pop(); // UNCOMMENT FOR OPTION B, to keep it of size n

  }
  console.log('for an array of size', n, 'the average time of', tries, 'splices was:', sum / tries);
 };
f();

Note that the code has an Option B, we did the same experiment for the three argument splice function to insert an element. It worked similary.

🌐
DEV Community
dev.to › salyadav › comment › 11k27
The problem with splice is, it has an O(n) time complexity in worst case. Sin... - DEV Community
... The problem with splice is, it has an O(n) time complexity in worst case. Since this question doesnot demand the exact array and bothers not about what exists after the returned length of the array...
Discussions

JavaScript runtime complexity of Array functions - Stack Overflow
Here is a complete explanation about time complexity of Arrays in JavaScript. ... Yes, exactly! Array.prototype.splice is a universal multifunctional tool, and its complexity depends on what is done with it. For example, it can remove and/or add the last element (as push or pop), then complexity ... More on stackoverflow.com
🌐 stackoverflow.com
March 4, 2021
Time complexity with for loop and splice - Courses - Educative.io
What would be the time complexity for the following code? Is it O(n^2)? Because for loop is O(n), inside the for loop there is splice(), and splice() is O(n) as well. So the time complexity will be O(n^2)? Please correct me if I’m wrong. Thanks! Here is the code snippet: function removeEven(arr) ... More on discuss.educative.io
🌐 discuss.educative.io
0
August 21, 2019
javascript - what is the time complexity of array.splice(...array.splice()) - Stack Overflow
I was solving one of the leetcode question which is rotating array. I solve with O(N) by using two for loop but then my runtime was lower then this solution. My solution: runtime 80ms var rotate = More on stackoverflow.com
🌐 stackoverflow.com
Javascript - Time and space complexity of splice and concat inside loop - Stack Overflow
I have a problem which requires a string to be transformed into another one by appending copies of its' initial value to itself. The problem allows to remove single characters at some places. More on stackoverflow.com
🌐 stackoverflow.com
December 4, 2018
🌐
Reddit
reddit.com › r/compsci › time complexity of array.splice
r/compsci on Reddit: Time Complexity of Array.Splice
December 29, 2017 -

Time complexity of array.splice is worst-case O(n) because it has to potentially copy over all the elements.

Question 1: this means array.shift() is always O(n)? Or is it optimized somehow low-level where it just adjusts starting memory address?

Question 2: People say use a linked list instead of array if you repeatedly splice because deletion is O(1). But you'd still have to search through linked list to find element (which worst-case is still linear) because it's not indexed. So how do you index a linked list, so that deletion is ACTUALLY constant time? (also, is a language's implementation, like JS, of an array ever a linked list?)

Top answer
1 of 3
2
  1. Using copy on write, the copy can be avoided in some cases right up to the point where the data mutated. AFAIK, not many languages expose or even use COW. I've mostly only ever seen it referenced in OS design for things like process forking.

  2. Academics say to always use a linked list. However, practically, Array lists are almost always preferred. The problem with linked lists is that they are not cache friendly. In the worst case, your CPU has to go out and hit main memory for every single node accessed (millions of cycles per node!).

In contrast Array lists keep all the nodes in a contiguous block of memory. CPUs, when they access memory, will pull in a block of memory into cache. For traversal of an array, the cost can easily be in the 10s of cylces per element.

Further, the cost of adding to an array list isn't as bad as you might think. These lists will often overallocate so they can avoid copying over the data when you hit the end of the array.

And in practice, middle or beginning insertion just isn't all that common. You almost always do tail insertions with lists and very often you don't do any deletions at all!

So how do you index a linked list, so that deletion is ACTUALLY constant time?

You iterate and delete/split at the same time. You still have n time, but you don't end up with 2*n time. That is pretty much the case for a linked list, when you want to frequently go through the list and remove, split, or merge the list at various points based on the current element. Again, in practice this happens almost never.

also, is a language's implementation, like JS, of an array ever a linked list?

Depends. In fact, in javascript it could easily start out as a linked list and later be transformed into an array list based on jit optimizations.

2 of 3
2

From experience in implementation (JSC but I believe it’s similar in other engines) array.shift and unshift are amortized but generally O(1). Splice is interesting that engines will try to avoid “real” splicing depending on how the outputs are used

🌐
Medium
medium.com › @avinashkumar151199 › slice-and-splice-in-javascript-30e81e4ea997
Slice and Splice in JavaScript?. slice()-: Slice is used to get a new… | by Avinash Kumar | Medium
August 10, 2023 - splice()-: Splice is used to add/remove an element from the given array, it change the original array. The time complexity of spliceis O(n).
🌐
DEV Community
dev.to › lukocastillo › time-complexity-big-0-for-javascript-array-methods-and-examples-mlg
Time complexity Big 0 for Javascript Array methods and examples. - DEV Community
June 3, 2020 - Big-O means f(n) is less than a constant of O(g(n)). So in the worst case, splice may accept every element but on average it won't and a best-case scenario it would be zero or one element (if 0 isn't practical) at the end of the stack. For best-case big-omega is used (e.g., Ω(n)) and for average-case big-theta is used (e.g., Θ(n)). Notice the internal ligature of the big-theta vs that of a big O as it may be easy to mistake one for the other. ... What reference did you lean on to find their time complexity?
Top answer
1 of 3
186

The ECMA specification does not specify a bounding complexity, however, you can derive one from the specification's algorithms.

push is O(1), however, in practice it will encounter an O(N) copy costs at engine defined boundaries as the slot array needs to be reallocated. These boundaries are typically logarithmic.

pop is O(1) with a similar caveat to push but the O(N) copy is rarely encountered as it is often folded into garbage collection (e.g. a copying collector could only copy the used part of an array).

shift is at worst O(N) however it can, in specially cases, be implemented as O(1) at the cost of slowing down indexing so your mileage may vary.

slice is O(N) where N is end - start. Not a tremendous amount of optimization opportunity here without significantly slowing down writes to both arrays.

splice is, worst case, O(N). There are array storage techniques that divide N by a constant but they significantly slow down indexing. If an engine uses such techniques you might notice unusually slow operations as it switches between storage techniques triggered by access pattern changes.

One you didn't mention, is sort. It is, in the average case, O(N log N). However, depending on the algorithm chosen by the engine, you could get O(N^2) in some cases. For example, if the engine uses QuickSort (even with an late out to InsertionSort), it has well-known N^2 cases. This could be a source of DoS for your application. If this is a concern either limit the size of the arrays you sort (maybe merging the sub-arrays) or bail-out to HeapSort.

2 of 3
18

in very simple words

push -> O(1)

pop -> O(1)

shift -> O(N)

slice -> O(N)

splice -> O(N)

Here is a complete explanation about time complexity of Arrays in JavaScript.

🌐
Educative
discuss.educative.io › courses
Time complexity with for loop and splice - Courses - Educative.io
August 21, 2019 - What would be the time complexity for the following code? Is it O(n^2)? Because for loop is O(n), inside the for loop there is splice(), and splice() is O(n) as well. So the time complexity will be O(n^2)? Please correct me if I’m wrong. Thanks! Here is the code snippet: function removeEven(arr) ...
🌐
Medium
medium.com › @ashfaqueahsan61 › time-complexities-of-common-array-operations-in-javascript-c11a6a65a168
Time Complexities Of Common Array Operations In JavaScript | by Ashfaque Ahsan | Medium
September 4, 2019 - The same however cannot be said about Array.unshift(). Adding an element at the beginning of an array means the new element will have an index of 0. Which means that the index of every other element must be incremented by 1. So Array.unshift() has a Linear Time Complexity and is O(n). The Array.pop() and Array.shift() methods which are used to remove an element from the end and beginning of an array respectively, work similarly. Array.pop() is O(1) while Array.shift() is O(n). We can use the Array.splice() method to remove an element and/or insert elements at any position in an array.
Find elsewhere
Top answer
1 of 1
1

Array#splice is O(n) because it can shift up to each array element per call. See: What's the time complexity of array.splice in Google Chrome?

In determining the time complexity of an algorithm, as long as each O(n) operation is in series and the number of O(n) operations is a constant factor (which are the case here), it's still O(n). O(n2) is the consequence of nested loops; that is, for each n we perform another O(n) operation.

This code uses only two sequential calls to Array#splice along with an O(n) spread for a total of O(3n) which is equivalent to O(n).

"My runtime was slower" -- Time complexity and runtime are totally distinct things. Much of runtime rests on implementation details, fixed overhead expenses (constant factors) that are ignored by big O, how large LC's test cases are, the composition of the test cases, inaccuracies LC's test case measurement, etc. Use a benchmark under your own control on very large random inputs to be more certain. Two O(n) codes rarely exhibit identical performance characteristics--time complexity is only concerned with the rate of growth of an algorithm.

As for this particular comparison, keep in mind that builtin functions are highly optimized. I'm assuming this runs in NodeJS (V8), so many builtins are written in C++ (or Torque) (and V8 is not unique in this).

Implementing builtins natively at a lower-level means the memory is likely to be compact and regular so cache accesses benefit from locality, less pointer chasing, opportunities for stack allocation, etc. for loops in high-level code are harder to optimize. They involve index variables, performing comparisons, branching and so forth, all of which needs to be effectively translated to bytecode in a way that may be sub-optimal. In cases when the builtin implementation is in JS, the designers have done much work to make them as efficient as possible.

In Array#splice's case, it's written in Torque which is translated to efficient assembly.

In your code, let a = Array.from({length:nums.length}). Incurs allocation overhead for two objects.

In short: benchmark fairly, don't conflate complexity and speed, and use builtins whenever possible (use a profiler to determine rare cases when not to).

🌐
Plain English
plainenglish.io › community › how-to-use-javascript-array-splice-like-a-pro-0b1384
How to Use JavaScript Array Splice() Like a Pro
January 15, 2024 - Because you have to move all the other elements to make space or fill the gap. If you do it at the end of the array, it''s fast. Why? Because you don''t have to move anything else. The time complexity of the splice() method is O(n).
🌐
JavaScript in Plain English
javascript.plainenglish.io › under-the-hood-worst-case-complexities-workings-of-popular-js-array-methods-739d5fef314a
Worst Case Complexities & Workings of Popular JS Array Methods | JavaScript in Plain English
August 9, 2022 - Time complexity Big 0 for Javascript Array methods and examples. Big O Notation · Big O of Javascript arrays. The copyWithin() method · The at() method · The concat() method · values() method · unshift() method · toString() method · splice() method · sort() method ·
Top answer
1 of 1
3

Normally a question like this is quite difficult to give a definite answer to, because different implementations of Javascript have different time complexities for basic array operations (such as creating a new array of size n). Javascript arrays will typically be implemented either as dynamic arrays or hashtables, and these data structures have different performance characteristics.

So, there is no definitive time complexity for splice to remove one element from an array. What we can say is that removing one element takes linear time for a dynamic array, and as @Ry- points out in the comments, also linear time for a hashtable, because of the need to renumber the later indices. We can also say that it's highly likely one of these two data structures is used, and no sensible implementation will take more than linear time to do splice.

Either way, the worst case for your algorithm is when x = 'aa...aa' and y = 'abb...bb', i.e. x is n copies of 'a', and y is 'a' followed by (m - 1) copies of 'b'.

For a dynamic array or a hashtable, then the time complexity for just the splice operations is O(nm²). This is because the outer loop iterates O(nm) times (note the i-- inside the loop, which happens every time the letter 'b' needs to be removed), and the splice operation requires shifting or renumbering O(m) elements in yArr after index i.

But suppose some more exotic data structure is used which supports removing an element in sub-linear time (e.g. a skip list). In that case, the above only gives O(nm) times the complexity of the "remove" operation. But we haven't counted concat yet; this creates a new data structure and copies every item into it, which will still take linear time. concat is called O(n) times and takes an average of O(n + m) time per call, so the complexity of just the concat operations is O(n² + nm).

So the time complexity is very likely O(n² + nm²), and certainly at least O(n² + nm); not linear.


The space complexity is O(n), since the length of yArr is never more than twice as long as xArr.

🌐
CopyProgramming
copyprogramming.com › howto › what-is-the-time-complexity-of-array-splice-array-splice
Array.splice(): Understanding its Time Complexity - Javascript
May 4, 2023 - The time complexity of Array#splice is O(n) as it has the potential to shift every element in the array with each call.
🌐
JavaScript in Plain English
javascript.plainenglish.io › understanding-time-and-space-complexity-of-common-javascript-built-in-methods-39a3285a6409
Understanding Time and Space Complexity of Common JavaScript Built-in Methods | by Kyle Le | JavaScript in Plain English
April 14, 2023 - When writing JavaScript code, it’s important to consider the performance of the code you’re writing. One way to do this is to understand the time and space complexity of the built-in methods you’re using.
🌐
CopyProgramming
copyprogramming.com › howto › javascript-what-s-the-algorithmic-performance-of-splice
Exploring the Algorithmic Performance of the Splice Method in JavaScript - Javascript
May 21, 2023 - The time complexity is highly probable to be O(n² + nm²), and definitely not linear, with a minimum of O(n² + nm). The space required for yArr is at most twice the space needed for xArr , resulting in a space complexity of O(n). Javascript: What's the algorithmic performance of 'splice'?, ...
Top answer
1 of 3
22

You might consider whether you want to use an object instead; all JavaScript objects (including Array instances) are (highly-optimized) sets of key/value pairs with an optional prototype An implementation should (note I don't say "does") have a reasonable performance hashing algorithm. (Update: That was in 2010. Here in 2018, objects are highly optimized on all significant JavaScript engines.)

Aside from that, the performance of splice is going to vary a lot between implementations (e.g., vendors). This is one reason why "don't optimize prematurely" is even more appropriate advice for JavaScript applications that will run in multiple vendor implementations (web apps, for instance) than it is even for normal programming. Keep your code well modularized and address performance issues if and when they occur.

2 of 3
9

Here's a good rule of thumb, based on tests done in Chrome, Safari and Firefox: Splicing a single value into the middle of an array is roughly half as fast as pushing/shifting a value to one end of the array. (Note: Only tested on an array of size 10,000.)

http://jsperf.com/splicing-a-single-value

That's pretty fast. So, it's unlikely that you need to go so far as to implement another data structure in order to squeeze more performance out.

Update: As eBusiness points out in the comments below, the test performs an expensive copy operation along with each splice, push, and shift, which means that it understates the difference in performance. Here's a revised test that avoids the array copying, so it should be much more accurate: http://jsperf.com/splicing-a-single-value/19

🌐
Medium
medium.com › @chinweregina › object-array-time-and-space-complexity-in-javascript-00792792dfc5
Object/Array Time and Space Complexity in JavaScript | by Chinwe Regina | Medium
October 16, 2023 - The run-time of these methods grow with the inputs or O(n) because they impact all indexes in the array. · concat / slice/splice — O (n): Similar to shift and unshift, concat, slice, and splice have an O(n).
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Basic Algorithm Scripting: Slice and Splice (HELP with aspect of directions) - JavaScript - The freeCodeCamp Forum
November 18, 2018 - I’m trying to understand the directions for this algorithm and one of the directions is confusing me: “Begin inserting elements at index n of the second array.” The splice() and slice() I am looking up and working thr…
Top answer
1 of 2
7

(V8 developer here.)

Array.prototype.slice is O(n), where n is the number of elements in the slice.
String.prototype.slice is O(1), thanks to our implementation of SlicedStrings, which are just storing pointer, offset, length to the original string and avoid copying the characters (except when they're tiny, so that copying a handful of characters is actually cheaper and smaller than storing a reference; that's still O(1)).

The key difference is that strings are immutable, and arrays are not. When you do str1 = "Hello World"; str2 = str1.slice(2, 5);, since there is no way to modify str1's contents afterwards, str2 doesn't need to ensure that it's unaffected by any such modification.
When you do a = [1, 2, 3, 4]; b = a.slice(1, 3); a[1] = "changed"; console.log(b[0]);, then you expect to see 2, not "changed". That's why b has to be an actual copy. (In theory, a copy-on-write approach would be possible, but V8 doesn't do that for array slices.)

"Shallow copy" means that nested objects will not be copied. Example:

let nested = {property: "value"};
var a = [nested];
var b = a.slice(0, 1);
a[0].property = "new value";
console.log(a === b);          // false, `b` is a copy
console.log(a[0] === b[0]);    // true, `nested` was not copied
console.log(b[0] === nested);  // true
console.log(b[0].property);    // "new value"
2 of 2
0

Based on my read (which is to say, I could be wrong, since V8 is a complicated beast) of this array-slice.tq source code, the answer is: "it depends".

If possible (and the heuristics as to when that might happen I didn't really get to), V8 optimizes things to essentially O(1) by just returning a copy-on-write view to the original array via ExtractFastJSArray.

When that fails, V8 allocates a new array and copies object (pointers) over, which is of course O(N).

The tq source code includes lots of "gotcha" cases, since JavaScript does allow you to call Array.prototype.slice() on things that aren't really arrays.

🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-splice-duplicate-item-from-javascript-array
How to Splice Duplicate Item from JavaScript Array? - GeeksforGeeks
July 23, 2025 - Example: Implementation of program to splice duplicate item in array using set · JavaScript · const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5]; const uniqueSet = new Set(); for (let i = 0; i < arr.length; i++) { const el = arr[i]; if (uniqueSet.has(el)) { arr.splice(i, 1); i--; } else { uniqueSet.add(el); } } console.log(arr); Output · [ 1, 4, 6, 2, 5, 8, 7 ] Time Complexity: O(n^2) Space Complexity: O(n) In this approach we are using the reduce method.