type Person struct {
Id int
First_Name string
Last_Name string
}
func person_new() *Person{
var b *Person = new(Person)
b.Id=1
b.First_Name="John"
b.Last_Name = "Hernandez"
return b;
}
func person_new2() *Person{
var b Person;
b.Id=1
b.First_Name="John"
b.Last_Name = "Hernandez"
return &b;
}
These two functions do exactly the same thing but my question is the first one is more inefficient right? In the first function, I will reserve more memory because I have to reserve space to my struct Person and to my pointer and in the second one only I will reserve space to my struct, right? And because I create a pointer to my struct (Person), the access to my attributes (Id, First_name, Last_name) will be slower than function 2 (I have to access to my pointer=&Person (put it in a register) and only then I will be able to access to my attributes)?
Because in both cases you return the address of the newly constructed structure. From the point of view of the caller of this code there is no difference.
Yes you are right i said that, in my post (“These two functions do exactly the same”) but my question is about efficiency. In first one i reserve space to a struct and to a pointer that point to the space that i created. But in second one i only have a struct not a pointer, so i will use less memory in function two, right?
You are returning a pointer, so certainly there exists a pointer. But you can discover the difference for yourself; put the above in a file with a package declaration, go build -gcflags -S thefile.go to get the assembly output. Diff the two functions. After removing the line numbers, the following differences remain for me:
The only difference is that in one case it needs the address of the symbol b (when it is not a pointer by itself), in the other it is already a pointer. I suspect that in the end these are the same instructions anyway. There is no other difference in the generated code. Specifically, the number of allocations is identical.