Files
learngo/16-slices/exercises/24-fix-the-memory-leak/solution/main.go

57 lines
1.4 KiB
Go
Raw Normal View History

2019-03-05 23:32:32 +03:00
// For more tutorials: https://blog.learngoprogramming.com
//
// Copyright © 2018 Inanc Gumus
// Learn Go Programming Course
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
//
package main
import (
"fmt"
"io/ioutil"
"github.com/inancgumus/learngo/16-slices/exercises/24-fix-the-memory-leak/solution/api"
)
func main() {
// reports the initial memory usage
api.Report()
// reads 65 MB of temperature data into the memory!
temps := api.Read()
2019-08-18 13:29:12 +03:00
// ------------------------------------------------------
2019-03-05 23:32:32 +03:00
// SOLUTION #1:
2019-08-18 13:29:12 +03:00
// ------------------------------------------------------
2019-03-05 23:32:32 +03:00
2019-08-18 13:29:12 +03:00
//
// Copy the last 10 elements of the returned temperatures
// to a new slice.
//
// This will create a new backing array.
//
2019-03-05 23:32:32 +03:00
need := make([]int, 10)
copy(need, temps[len(temps)-10:])
//
2019-08-18 13:29:12 +03:00
// Make the temp slice lose reference to its backing array
// so that its backing array can be cleaned from the memory.
2019-03-05 23:32:32 +03:00
//
2019-08-18 13:29:12 +03:00
temps = need
// ------------------------------------------------------
// SOLUTION #2:
// ------------------------------------------------------
// Similar to the 1st solution. It does the same thing.
// But this code is more concise. Use this one.
2019-03-05 23:32:32 +03:00
// temps = append([]int(nil), temps[len(temps)-10:]...)
2019-08-18 13:29:12 +03:00
// ------------------------------------------------------
// don't worry about this code yet.
2019-03-05 23:32:32 +03:00
api.Report()
fmt.Fprintln(ioutil.Discard, temps[0])
}