Tuesday, May 13, 2025
HomeGolangBase struct as pointer or sub structs as pointers - Getting Assist

Base struct as pointer or sub structs as pointers – Getting Assist


Hello,

I used to be questioning is there may be any distinction (by way of environment friendly reminiscence utilization) between variations under. First one is returned as pointer however not its inside objects. Second model makes use of inside objects as pointer however not the bottom one.

Notice: Objects can get massive, I stored them small for now. FYI – BulkResponse just isn’t meant to be mutated in any respect. It’ll simply be returned from one package deal to a different, that’s it.

Thanks

V1

kind Response struct {
	Period   int 
	Success    bool
	Operations []Operation
}

kind Operation struct {
	Create Merchandise
	Replace Merchandise
	Delete Merchandise
	Checklist   Merchandise
}

kind Merchandise struct {
	ID     string 
	Errors []Error
}

kind Error struct {
	Code    int
	Cause  string
	Message string
}

func Version1() *BulkResponse {
	res := &BulkResponse{}
	// Construct response ....
	return res
}

V2

kind Response struct {
	Period   int 
	Success    bool
	Operations []*Operation
}

kind Operation struct {
	Create Merchandise
	Replace Merchandise
	Delete Merchandise
	Checklist   Merchandise
}

kind Merchandise struct {
	ID     string 
	Errors []*Error
}

kind Error struct {
	Code    int
	Cause  string
	Message string
}

func Version2() BulkResponse {
	res := BulkResponse{}
	// Construct response ....
	return res
}

That is related in nature to this query the place I posted a bunch of knowledge that you simply may discover useful:

And in that thread I told the OP to benchmark it:

Which is exactly what I think you should do. Write some benchmarks and test memory usage. Also if you really want to get into memory optimization of your structs, you could take a look at padding/alignment. There’s a tool you can use to analyze your project:

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments