Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove and store an array item without creating garbage

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?

like image 953
jackrugile Avatar asked May 25 '26 01:05

jackrugile


1 Answers

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
like image 125
Esailija Avatar answered May 27 '26 14:05

Esailija



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!