Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between pointer and value in struct?

Given the following struct:

type Exp struct {
  foo int,
  bar *int
}

What is the difference in term of performance when using a pointer or a value in a struct. Is there any overhead or this just two schools of Go programming?

I would use pointers to implement a chained struct but is this the only case we have to use pointers in struct in order to gain performance?

PS: in the above struct we talk about a simple int but it could be any other type (even custom one)

like image 922
fsenart Avatar asked Jun 27 '14 12:06

fsenart


People also ask

What is difference between pointer and structure?

A pointer is something that point to the address of any variable, including a structure. A structure is sort of like a collection of variables except that it can include multiple types which each have names.

What is a struct pointer?

Structure pointer points to the address of the structure variable in the memory block to which it points. This pointer can be used to access and change the value of structure members. This way, structures and pointers in C can be used to conveniently create and access user-defined data types.

Why do we use pointers for structs?

Pointers are helpful because you can "move them around" more easily. Instead of having to copy over the whole stucture each time, you can just leave it where it is in memory and instead pass a pointer to it around.


Video Answer


1 Answers

Use the form which is most functionally useful for your program. Basically, this means if it's useful for the value to be nil, then use a pointer.

From a performance perspective, primitive numeric types are always more efficient to copy than to dereference a pointer. Even more complex data structures are still usually faster to copy if they are smaller than a cache line or two (under 128 bytes is a good rule of thumb for x86 CPUs).

When things get a little larger, you need to benchmark if performance concerns you. CPUs are very efficient at copying data, and there are so many variables involved which will determine the locality and cache friendliness of your data, it really depends on your program's behavior, and the hardware you're using.

This is an excellent series of articles if you want to better understand the how memory and software interact: "What every programmer should know about memory".

In short, I tell people to choose a pointer or not based on the logic of the program, and worry about performance later.

  • Use a pointer if you need to pass something to be modified.
  • Use a pointer if you need to determine if something was unset/nil.
  • Use a pointer if you are using a type that has methods with pointer receivers.
like image 108
JimB Avatar answered Sep 18 '22 12:09

JimB