Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: What's the algorithmic performance of 'splice'?

That is, would I be better suited to use some kind of tree or skip list data structure if I need to be calling this function a lot for individual array insertions?

like image 456
Hamster Avatar asked Nov 19 '10 18:11

Hamster


People also ask

How fast is splice JavaScript?

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.) That's pretty fast.

Is array splice slow?

splice() is several orders of magnitude slower than a for loop iterating through the elements. This lead me to wonder why Array. splice() is so slow.

What does JavaScript Splice do?

The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. To access part of an array without modifying it, see slice() .

Is it good to use splice ()?

Great job! The splice() method is mostly used when you need to delete or add new elements to an array. In some situations, you can also use it to separate an array which has mixed content as in the case above. When you remove 0 elements from the array, then the method will simply return an empty array.


1 Answers

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.

like image 119
T.J. Crowder Avatar answered Sep 21 '22 04:09

T.J. Crowder