Passing a struct vs pass struct pointer

I recently wrote a lot of programs that skip structaround functions to avoid global variables. However, I was wondering if the transfer structitself or its pointer is more efficient . It seems like it should be because pointers (on my 64-bit GNU / Linux system) contain 8 bytes, and structwith a lot of pointers, obviously a lot more.

However, if I have this struct:

struct Point {
    int x;
    int y;
}

which is 8 bytes, the same size as the pointer, is it better to pass the entire function to a structfunction or pass a pointer? I'm pretty good at C memory allocation, so mallocfriends should not be used when initializing pointers .

Another thought I had was that the transfer structures could directly use a lot of stack space if they were large. However, just using pointers will use memory, which can be easy free.

+4
source share
1 answer

[ This question , and it answers a rather thorough general attitude to the pros and cons of transferring structures and pointer structures. This answer intends to consider the specific case mentioned in this question, i.e. An 8-byte struct vs an 8-byte pointer and an ABI that passes arguments to registers.]

64- Intel Linux ABI , 8 , . %rdi. . ABI .

(8- struct vs 8- ) . .. . , , :

int
add (struct Point p)
{
  return p.x + p.y;
}

.. gcc -O1, .

(x86_64 Linux gcc 5.1, -O1):

# Passing the struct:
movq    %rdi, %rax
sarq    $32, %rax
addl    %edi, %eax
ret

# Passing a pointer to the struct:
# [each (%rdi) is a memory access]
movl    4(%rdi), %eax
addl    (%rdi), %eax
ret

, , . , . . , , , . , , , , , .

32- Linux int 4 , (8 4). , , 4 (8- , vs 4- ). - - .

+7

Source: https://habr.com/ru/post/1619492/


All Articles