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,我可以想到两种方法:
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?
两种方法之间是否存在性能差异,如果不存在,建议使用哪种方法?
4 个解决方案
#1
3
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.
它们都具有相同的时间复杂度。性能上的任何其他差异都可能是由于特定情况,例如CPU,编译器,memmove的实现方式以及阵列的大小,因此您必须实际测量每种方式的性能并查看最佳性能。
#2
7
There is a faster option:
有一个更快的选择:
A circular buffer where insert, remove and read are all O(1).
一个循环缓冲区,其中插入,删除和读取都是O(1)。
#3
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.
我不认为数组是最好的方法,尝试使用链表,你不会有这个问题。
#4
0
You can use the FIFO Queue implemented as a linked list or as an array. From your description, it's the most straightforward solution.
您可以将FIFO队列用作链接列表或数组。根据您的描述,这是最直接的解决方案。
#1
3
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.
它们都具有相同的时间复杂度。性能上的任何其他差异都可能是由于特定情况,例如CPU,编译器,memmove的实现方式以及阵列的大小,因此您必须实际测量每种方式的性能并查看最佳性能。
#2
7
There is a faster option:
有一个更快的选择:
A circular buffer where insert, remove and read are all O(1).
一个循环缓冲区,其中插入,删除和读取都是O(1)。
#3
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.
我不认为数组是最好的方法,尝试使用链表,你不会有这个问题。
#4
0
You can use the FIFO Queue implemented as a linked list or as an array. From your description, it's the most straightforward solution.
您可以将FIFO队列用作链接列表或数组。根据您的描述,这是最直接的解决方案。