I
I
iliyaisd2018-10-30 19:06:43
go
iliyaisd, 2018-10-30 19:06:43

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

2 answer(s)
T
Tyranron, 2018-10-30
@Tyranron

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:

  1. var i int
    i = 1
    i = 2

    0 allocations, since it iis placed strictly on the stack.
  2. i := 1
    i := 2

    0 allocations, since it iis placed strictly on the stack.
  3. i := new(Struct{1,2,3})
    i := new(Struct{3,2,1})

    2 allocations, since it newwill 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).
  4. var i *Struct
    i = new(Struct{1,2,3})
    i = new(Struct{3,2,1})

    2 allocations, since it newwill still allocate the data on the heap and return a pointer to it.
    As you can see, :=in itself it does not apply to allocations in any way, and is only syntactic sugar.
    PS Recently on Habré there was an excellent article about the Go standard library, showing that doing premature micro-optimizations without profiling is a completely pointless undertaking.

G
golangmoses, 2018-11-08
@golangmoses

use sync.Pool

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question