I have a discussion on this topic with my colleagues and is curious to see how the community see it.
In terms of idiomatic or style, between the two usage patterns, if I want to use a variable to hold a slice of structs, are there any prevailing preference for one pattern over another between []*Person and []Person below?
Say, for example, for this simple struct.
type Person struct {
name string
surname string
address string
age int
}
If there is no style guide over this, in what scenarios one is preferred over the other.
FYI.
I run a simple benchmark test on slice creation, and it seems that []*Person performs a bit better than []Person.
I presume this is because of the cost of copying the struct's value into slice's underlying array when a struct is appended to the slice.
package main
import (
"testing"
)
type Person struct {
name string
surname string
address string
age int
}
func BenchmarkCreatingSliceOfStruct(b *testing.B) {
persons := []Person{}
for i := 0; i < b.N; i++ {
persons = append(persons, Person{name: "ABCDEF", surname: "ABCDEF", address: "123456", age: 2005})
}
}
func BenchmarkCreatingSliceOfPointersToStruct(b *testing.B) {
persons := []*Person{}
for i := 0; i < b.N; i++ {
persons = append(persons, &Person{name: "ABCDEF", surname: "ABCDEF", address: "123456", age: 2005})
}
}
And, this is the result.
/home/_/src/slice$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkCreatingSliceOfStruct-12 1000000 1405 ns/op
BenchmarkCreatingSliceOfPointersToStruct-12 10000000 252 ns/op
ok slice 4.258s