c - 数组处理的性能差异

标签 c memory struct runtime

我有这个代码:

typedef struct
{
int a[4];
} ArrStruct;

void printSizeOfArray(ArrStruct arrStruct)
{
printf("%lu\n", sizeof(arrStruct.a));
++(arrStruct.a[2]);
}

int main()
{

int it;
ArrStruct arrStruct;
printSizeOfArray(arrStruct);

for (it = 0 ; it < sizeof(arrStruct.a)/sizeof(int); ++it)
{
printf("%d, ", arrStruct .a[it]);
}

return 0;
}

有人告诉我,与下一个代码相比,它没有良好的运行时/内存性能。有什么区别?

void printSizeOfArray(int a[])

{
printf("%lu\n", sizeof(a));
++(a[2]);
}

int main()
{

int it;
int a[4] = {0};
printSizeOfArray(a);
for (it = 0 ; it < sizeof(a)/sizeof(int) ; ++it)
{
printf("%d, ", a[it]);
}
return 0;
}

为什么第二个代码会有更好的性能?

最佳答案

在第一个代码中,结构体ArrStruct是按值使用的,因此,在函数printSizeOfArray中,结构体的成员a不会被转换为指针。因此,堆栈上将会有更多的 4 * sizeof(int) - sizeof(int *) (加上潜在的填充字节)。检查生成的程序集,了解第一个代码还是第二个代码效率更高。

理论上,第二个代码会运行得更快,因为取消引用更少。但是,打开优化后,没有显着差异。

关于c - 数组处理的性能差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13235572/

相关文章:

c - C 代码中没有重复

c - 在函数的参数中声明指针类型以修改链表

c - 将已知大小的二维数组转换为使用 malloc 代替 C 中函数的数组的步骤是什么?

.net - 即使应用似乎没有占用最大内存量,也会发生OutOfMemoryException

matlab - 如何在不使用访问任何元素的情况下对结构的所有字节进行操作?

c++ - 如何将 JsonObject 转换为 JSON 字符串?

c - 选择排序不排序

Android setBackgroundResource 导致内存不足异常

c++ - 如何将 std::vector 的容量限制为元素的数量

c - 难以理解 C 中的结构