Fast JavaScript array concatenation

Suppose we want to write a concat() function in JavaScript that takes as input a variable number of elements, which can be either simple elements (like a number or a word) or arrays. We want that function to return an array that contains the concatenation of all the simple elements or arrays passed as input parameters.

First of all, we know we can iterate on the arguments implicit parameter, which is an array containing all the arguments passed as input to the function. As we said, each of these parameters can be a simple element or an array; thus we perform a check to determine the type of the element we are dealing with and, in the case of an array, we iterate on it.

Now, the important part. The easiest way to concatenate the elements would be to create an empty array and then call push() on it to insert every element at the end of it. The problem with this approach is that it forces the array to resize every time we add a new element.

A much faster approach is thus to determine the size of the resulting array and then create it by specifing the exact size. In this way we don’t need to ever resize the array; plus, we are keeping track of the current index so that we don’t need to determine the index of the lastly inserted value, increment it by one, insert the current item and repeat the operation.

The code below is an example of a concat() function that performs the fast concatenation:

function concat() {
    var i, j, ar, item, k = 0;
    for (i = 0; i < arguments.length; i++) {
        item = arguments[i];
        if (Arrays.isArray(item)) {
            k += item.length;
        } else {
            k++;
        }
    }
    ar = new Array(k);
    k = 0;
    for (i = 0; i < arguments.length; i++) {
        item = arguments[i];
        if (Arrays.isArray(item)) {
            for (j = 0; j < item.length; j++) {
                ar[k] = item[j];
                k++;
            }
        } else {
            ar[k] = item;
            k++;
        }
    }
    return ar;
}
 
0
Kudos
 
0
Kudos

Now read this

using f.lux

I was very skeptical at first about f.lux: I didn’t see how turning my display colors towards red could help my eyes be less strained while programming late in the evening. After some time I decided to give it a try and here I am, after... Continue →