Background
Much of Go is introverted and advocates the boulevard to Jane, but we've also seen some of the more demanding business scenarios, such as some of the game's business scenarios, using technical means such as CGO to bypass go garbage collection. So, we do not have to look at all the eyes on the 95%, there are still 5% of the situation is that we need to deal with. Even today, memory is still a very scarce resource, so we can imagine how to manage and allocate memory resources, which is a very challenging topic.
Let's take a look at this code and see what happens to the memory.
package mainfunc A() *int { x := 100 return &x}
But if someone with C-language experience knows that this code is problematic, let's simply test the code.
package mainimport "testing"func BenchmarkA (b *testing.B){ for i := 0; i < b.N; i++{ A() }}
go test -v -test.bench . -benchmemafter execution, the test results are as follows:
goos: darwingoarch: amd64pkg: golang/runtimeBenchmarkA-4 2000000000 0.32 ns/op 0 B/op 0 allocs/opPASSok golang/runtime 0.739s
Feel no problem, just do the performance test, then I do not modify the parameters of the case, add a parameter, prohibit the function inline, we will test again
Execute, go test -v -test.bench . -benchmem -gcflags -l continue, test the situation as follows:
goos: darwingoarch: amd64pkg: golang/runtimeBenchmarkA-4 100000000 15.8 ns/op 8 B/op 1 allocs/opPASSok golang/runtime 1.646s
We can see the performance degradation is very serious, the key is that every time it executes will be in memory once
Allocation, 64-bit system is 8 bytes (integer pointer), obviously, go for memory allocation of this behavior is determined by the runtime and the compiler, and we write the code regardless, that is, when we write this code, we do not guarantee that our variables are allocated on the stack or on the heap.
Applications may not be very concerned at times, but we can imagine how much pressure the GC will have on the hundreds of thousands of temporary objects that are allocated hundreds of thousands of temporary objects in memory every second. Because sometimes garbage collection does not care about you this object is big or small, and care about you this object how many, why? Because he needs to check that each of your objects is not up to date, he needs to keep all the available objects and reclaim all the unreachable objects. That is, the more temporary objects on the heap in a unit of time, the greater the pressure on garbage collection. A small control switch can have a big impact on your performance. there is an allocation on the stack, which becomes allocated on the heap.
Memory Allocator origin
Memory Unit
Initialization and basic architecture
Memory allocation
Memory Recycling
Physical Memory Release