Answer the question
In order to leave comments, you need to log in
Should the := assignment sign be avoided in Go when the backend is loaded?
Subject. As I understand it, with := on Go, memory allocation occurs, which can play a cruel joke under load. Is it worth it, if possible, to create variables as early as possible and through var? Or does it not matter?
Thank you.
Answer the question
In order to leave comments, you need to log in
It does not matter.
You should not "save on matches" and observe empty rituals. You write the application normally so that other developers understand and read it normally. When it comes to optimization, you profile and see where exactly you have problems and plugs. You remove them.
As for allocations specifically, everything is not quite right (or rather, not at all like that).
Allocation is the allocation of a piece of memory on the heap ( heap ), which then must be removed by the garbage collector. This is why this is considered a performance hit, as it adds work to both the allocator and the garbage collector.
But usage :=
by itself does not enable/disable the use of allocation. It only declares a new variable.
Whether an allocation will be made depends on another. First of all, on what kind of data you create. If this is a fixed-size primitive type placed on the stack (for example int
, ), then you will not have any work with the heap at all, and accordingly, allocations. Secondly, from such a magical thing as escape analysis , which can easily place data from the heap on the stack, if it so wants, then you will not have an allocation either.
Let's see some examples:
var i int
i = 1
i = 2
i
is placed strictly on the stack.i := 1
i := 2
i
is placed strictly on the stack.i := new(Struct{1,2,3})
i := new(Struct{3,2,1})
new
will allocate data on the heap and return a pointer to them. But only if escape analysis doesn't push it all onto the stack (which in this particular case is quite likely).var i *Struct
i = new(Struct{1,2,3})
i = new(Struct{3,2,1})
new
will still allocate the data on the heap and return a pointer to it.:=
in itself it does not apply to allocations in any way, and is only syntactic sugar. Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question