将结构传递给函数
在 C 中,所有参数都按值传递给函数,包括结构。对于小结构,这是一件好事,因为这意味着通过指针访问数据没有任何开销。但是,它也很容易意外地传递一个巨大的结构导致性能不佳,特别是如果程序员习惯于通过引用传递参数的其他语言。
struct coordinates
{
int x;
int y;
int z;
};
// Passing and returning a small struct by value, very fast
struct coordinates move(struct coordinates position, struct coordinates movement)
{
position.x += movement.x;
position.y += movement.y;
position.z += movement.z;
return position;
}
// A very big struct
struct lotsOfData
{
int param1;
char param2[80000];
};
// Passing and returning a large struct by value, very slow!
// Given the large size of the struct this could even cause stack overflow
struct lotsOfData doubleParam1(struct lotsOfData value)
{
value.param1 *= 2;
return value;
}
// Passing the large struct by pointer instead, fairly fast
void doubleParam1ByPtr(struct lotsOfData *value)
{
value->param1 *= 2;
}