Best way to shift an array in C?

19,092

Solution 1

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.

Solution 2

There is a faster option:

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

Solution 3

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.

Share:
19,092
Maestro
Author by

Maestro

Updated on June 04, 2022

Comments

  • Maestro
    Maestro almost 2 years

    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?

  • chrylis -cautiouslyoptimistic-
    chrylis -cautiouslyoptimistic- over 10 years
    Reading the assembly output might also be instructive.