下面这段代码:
```go
package main
import (
"fmt"
"runtime"
"unique"
)
func printMemUsage() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("Alloc = %v B", m.Alloc)
fmt.Printf("\tTotalAlloc = %v B", m.TotalAlloc)
fmt.Printf("\n")
}
type TestStruct struct {
A float64
B float64
C float64
D float64
}
func main() {
testobj1 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
testobj2 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
testobj3 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
testobj4 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
fmt.Println(testobj1, testobj2, testobj3, testobj4)
fmt.Println("---------")
uniqueobj1 := unique.Make(TestStruct{A: 1, B: 2, C: 3, D: 4})
printMemUsage()
uniqueobj2 := unique.Make(TestStruct{A: 1, B: 2, C: 3, D: 4})
printMemUsage()
uniqueobj3 := unique.Make(TestStruct{A: 1, B: 2, C: 3, D: 4})
printMemUsage()
uniqueobj4 := unique.Make(TestStruct{A: 1, B: 2, C: 3, D: 4})
printMemUsage()
fmt.Println(uniqueobj1, uniqueobj2, uniqueobj3, uniqueobj4)
fmt.Println("---------")
testobj5 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
testobj6 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
testobj7 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
testobj8 := TestStruct{A: 1, B: 2, C: 3, D: 4}
printMemUsage()
fmt.Println(&testobj5, &testobj6, &testobj7, &testobj8)
}
```
输出结果是:
```
Alloc = 118256 B TotalAlloc = 118256 B
Alloc = 119704 B TotalAlloc = 119704 B
Alloc = 119720 B TotalAlloc = 119720 B
Alloc = 119736 B TotalAlloc = 119736 B
{1 2 3 4} {1 2 3 4} {1 2 3 4} {1 2 3 4}
---------
Alloc = 121056 B TotalAlloc = 121056 B
Alloc = 121072 B TotalAlloc = 121072 B
Alloc = 121088 B TotalAlloc = 121088 B
Alloc = 121104 B TotalAlloc = 121104 B
{0x1400001e180} {0x1400001e180} {0x1400001e180} {0x1400001e180}
---------
Alloc = 121152 B TotalAlloc = 121152 B
Alloc = 121200 B TotalAlloc = 121200 B
Alloc = 121248 B TotalAlloc = 121248 B
Alloc = 121296 B TotalAlloc = 121296 B
&{1 2 3 4} &{1 2 3 4} &{1 2 3 4} &{1 2 3 4}
```
本来是想试一下 unique 包对于内存的节约效果的,但是没想到第一种写法,每次也只增加了 16B ,和用了 unique 效果一样
而第三种写法,和第一种相比,确实每次用的内存多了,但是为什么后面的 fmt.Println 的写法区别,能影响前面的内存使用量
版本:go 1.23.0
平台:arm macos |
|