A good source for this: https://100go.co/
Strings
- len does not return the number of characters: Strings
Maps
Maps don't free that much memory as they shrink.
Shoutouts to: https://100go.co/28-maps-memory-leaks/
func main() {
n := 1_000_000
m := make(map[int][128]byte)
printAlloc()
for i := 0; i < n; i++ { // Adds 1 million elements
m[i] = [128]byte{}
}
printAlloc()
for i := 0; i < n; i++ { // Deletes 1 million elements
delete(m, i)
}
runtime.GC() // Triggers a manual GC
printAlloc()
runtime.KeepAlive(m) // Keeps a reference to m so that the map isn’t collected
}
func printAlloc() {
var m runtime.MemStats
runtime.ReadMemStats(&m)
fmt.Printf("%d MB\n", m.Alloc/(1024*1024))
}
Will print:
0 MB
382 MB
287 MB
TL:DR; Go Maps grow but never shrink. To avoid this, re-assign the map.
Passing references and copies
As in other programming languauges, passing to functions might use copies or references Passing references and values
Almost identical functions, but the latter one will alter the original slice:
func alterPeople(arr []string) {
arr = append(arr, "John")
}
func alterPeopleInplace(arr []string) {
arr[0] = "John"
}
func main() {
people := []string{"Max", "Tom"}
alterPeople(people)
fmt.Println(people) // ["Max", "Tom"]
alterPeopleInplace(people)
fmt.Println(people) // ["John", "Tom"]
}