將結構傳遞給函式

在 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;
}