refactor: slice exercises 22 and 24

This commit is contained in:
Inanc Gumus
2019-08-22 20:55:47 +03:00
parent 792a7a75d4
commit 08d881a3d0
6 changed files with 126 additions and 73 deletions

View File

@ -6,9 +6,7 @@ import (
"runtime"
)
// DO NOT TOUCH THE FOLLOWING CODE
// THIS IS THE IMAGINARY API CODE
// YOU CANNOT CONTROL IT!
// DO NOT TOUCH THIS FILE BUT YOU CAN READ IT
// Read returns a huge slice (allocates ~65 MB of memory)
func Read() []int {

View File

@ -18,39 +18,35 @@ func main() {
// reports the initial memory usage
api.Report()
// reads 65 MB of temperature data into the memory!
temps := api.Read()
// returns a slice with 10 million elements.
// it allocates 65 MB of memory space.
millions := api.Read()
// ------------------------------------------------------
// SOLUTION #1:
// ------------------------------------------------------
// Copy the last 10 elements of the returned slice
// to a new slice. This will create a new backing array
// only with 10 elements.
last10 := make([]int, 10)
copy(last10, millions[len(millions)-10:])
//
// Copy the last 10 elements of the returned temperatures
// to a new slice.
//
// This will create a new backing array.
//
need := make([]int, 10)
copy(need, temps[len(temps)-10:])
// Make the millions slice lose reference to its backing array
// so that its backing array can be cleaned up from memory.
millions = last10
//
// Make the temp slice lose reference to its backing array
// so that its backing array can be cleaned from the memory.
//
temps = need
// ------------------------------------------------------
// SOLUTION #2:
// ------------------------------------------------------
// Similar to the 1st solution. It does the same thing.
// But this code is more concise. Use this one.
// temps = append([]int(nil), temps[len(temps)-10:]...)
// millions = append([]int(nil), millions[len(millions)-10:]...)
fmt.Printf("\nLast 10 elements: %d\n\n", last10)
// ------------------------------------------------------
// don't worry about this code yet.
api.Report()
fmt.Fprintln(ioutil.Discard, temps[0])
// don't worry about this code yet.
fmt.Fprintln(ioutil.Discard, millions[0])
}