Answer the question
In order to leave comments, you need to log in
What is the best way to shorten an array from the beginning: shift, splice or delete?
Objects arrive in sequence. It is necessary to store the last N objects in memory. Objects are voluminous in terms of occupied memory and the number N is large enough.
There is such an idea. We define an array arr and a variable i. As objects arrive, we write them to the array. If index i is less than maxi, then increase it by 1 and write to this address. If index i has reached maxi, then we apply the shift() method to the array, which removes the first element and shifts all indices, and writes it to the array at address i.
if( i<maxi ) i++; else arr.shift();
arr[i] = myobj;
Answer the question
In order to leave comments, you need to log in
Both shift and splice will actually shift all elements. No, an array is not implemented as a list. delete is also not optimal. But the aforementioned (in the comments to the question) ring buffer on an array of length N is ideal for your case.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question