Question

I have an array that holds a history of values, and when adding a new value, I need to shift all previous values one position to the left, to loose the oldest value and make room for the next.

I can think of two ways of doing this, by using memmove:

memmove(&arr[0], &arr[1], sizeof(arr) - sizeof(*arr));

Or by swapping the pointers:

for (i = 0; i != sizeof(arr) - 1; i++) {
   *(arr + i) = *(arr + i + 1);
}

Is there a performance difference between the two methods, and if not, which one would be advised?

Was it helpful?

Solution 2

They both have the same time complexity. Any other difference in performance would be due to specific circumstances, such as the CPU, the compiler, how memmove is implemented, and the size of the array, so you have to actually measure the performance each way and see what is best.

OTHER TIPS

There is a faster option:

A circular buffer where insert, remove and read are all O(1).

I don't think that an array is the best way to do this , try using a linked list and you wont have this problem.

You can use the FIFO Queue implemented as a linked list or as an array. From your description, it's the most straightforward solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top