E
E
Eugene Ordinary2021-07-18 23:47:47
JavaScript
Eugene Ordinary, 2021-07-18 23:47:47

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;

How is it optimal?

How is the shift() function implemented in javascript? Does it physically overwrite the array elements at new addresses, or is the array implemented as a list there and everything happens economically?

There is also an idea not to shift the elements of the array, but to constantly increase the index i, but remove elements from the beginning of the array using splice() or delete. Which way is better?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-07-19
@Alexandroppolus

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 question

Ask a Question

731 491 924 answers to any question