Frage

I'm looking for a performant way to remove and store elements from an array. I am trying to make an object pool to reduce garbage collections calls.

Just as .pop() and .unshift() remove elements from an array and return the value of that element, I'd like to be able to remove an element at a specific index, while storing it's value in a variable, and while not creating unnecessary arrays/objects.

.splice() removes the element at a specific index just fine, and stores that value in an array. I can access that, but the function itself creates a new array, which will eventually trigger the garbage collector.

.slice() has the same issue, a new array is created.

Is there a way to pull out and store a specific indexed element without the creation of a new array?

War es hilfreich?

Lösung

This always removes one item at index, if you need to remove more than 1 consecutive items at a time, it would be more efficient to implement it to take a howMany argument and remove them in a batch instead of calling removeAt repeatedly.

function removeAt(array, index) {
    // Assumes array and index are always valid values
    // place validation code here if needed
    var len = array.length;
    // for example if index is not valid here, it will deoptimize the function
    var ret = array[index];
    for (var i = index + 1; i < len; ++i) {
        array[i - 1] = array[i];
    }
    array.length = len - 1;
    return ret;
}

Usage:

var a = [1,2,3,4,5]
var removed = removeAt(a, 2);
console.log(a);
// [1, 2, 4, 5]
console.log(removed);
// 3
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top