Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript concat running time

If I have two arrays both with 10000 items, now I want to merge them into one array, so I do it with concat:

 array1=array1.concat(array2);

but does any body know what is the running time? constant or N? is there a better way to merger them in term of speed. thanks for any tips.

like image 280
bingjie2680 Avatar asked Dec 08 '11 17:12

bingjie2680


People also ask

Is concat faster than push?

concat returns a new array while push returns the length of updated array. Because concat creates a new array to hold the result of merged arrays, it's slower than push . For small arrays, both methods do not produce a significant difference in term of performance.

What is the time complexity of string concatenation Javascript?

String concatenation It can be a bit surprising, but this code actually runs in O(N2) time. The reason is that in Java strings are immutable, and as a result, each time you append to the string new string object is created.

What does concat do javascript?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

How to concat 2 arrays js?

You can use either the spread operator [... array1, ... array2] , or a functional way []. concat(array1, array2) to merge 2 or more arrays.


1 Answers

I doubt that the ECMAScript specification mandates any big-oh performance requirements for any operations, so it will be implementation dependent. The only way to verify would be to write a benchmark and run it on your target interpreters.

That said, I would guess that most JavaScript interpreters implement Arrays as vector-type arrays rather than linked lists, so the concat operation is likely to be O(n) on most engines.

like image 172
maerics Avatar answered Oct 13 '22 10:10

maerics