Addition or deletion of elements of a dynamic array

arraydynamicmutable

Is there any consensus among programmers (or a common convention) on the "right way" to deal with the addition or deletion of one or more elements of a dynamic (mutable) array at runtime while gracefully handling changes to the references to the other elements?

For example within a loop in JavaScript, to remove some elements

  • does one use delete() to replace the items with 'undefined' while keeping the length of the array unchanged, so that references to the other elements have not changed?
  • Or do you slice() or splice(x,1) the array and then somehow update all current references?
  • Or do you make a copy of the array at the beginning of a function call, for example, then use delete() while still in that function, then at the end use filter() to remove the undefined slots and then write that back out to the original object?

What if more than one user or thread is trying to access this array simultaneously? Is the only choice a locking mechanism for writes? Or perhaps the answer is simply, "it just depends on what you want/need it to do".

Thanks in advance for your opinions.

Best Answer

The consensus I am aware of (I only know a couple languages, not all of them) is as follows:

If the use of the array is somewhat complex, such as in the case of multithreaded access to the array, the array is put in a wrapper class. The wrapper class then exposes the minimum necessary amount of operations that can be performed on the array.

If the use is simple and the array is used synchronously, then it doesn't matter as long as the code has a good balance in terms of performance and being readable. Where that balance lies depends on the requirements, but it's usually "As readable as possible while being fast enough".