refactor: slices 24th exercise

This commit is contained in:
Inanc Gumus
2019-08-18 13:29:12 +03:00
parent dfca449457
commit df18e1a4bd
4 changed files with 81 additions and 29 deletions

View File

@ -7,15 +7,29 @@ import (
)
// DO NOT TOUCH THE FOLLOWING CODE
// THIS IS THE API
// YOU CANNOT CONTROL IT! :)
// THIS IS THE IMAGINARY API CODE
// YOU CANNOT CONTROL IT!
// Read returns a huge slice (allocates ~65 MB of memory)
func Read() []int {
// 2 << 22 means 2^(22 + 1)
// See this: https://en.wikipedia.org/wiki/Arithmetic_shift
// Perm function returns a slice with random integers in it.
// Here it returns a slice with random integers that contains
// 8,388,608 elements. One int value is 8 bytes.
// So: 8,388,608 * 8 = ~65MB
return rand.Perm(2 << 22)
}
// Report cleans the memory and prints the current memory usage
// Don't worry about this code. You don't need to understand it.
//
// However, if you're curious, read on.
//
// The following code runs the garbage collector to clean
// up the allocated resources, and then it reads the current
// memory statistics into the m variable.
func Report() {
var m runtime.MemStats
runtime.GC()

View File

@ -21,25 +21,36 @@ func main() {
// reads 65 MB of temperature data into the memory!
temps := api.Read()
//
// ------------------------------------------------------
// SOLUTION #1:
//
// ------------------------------------------------------
// clone the last 10 elements of the returned temperatures
// into a new slice
//
// 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 temp slice lose reference to its backing array
// so that it can be cleaned from the memory
//
// 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.
// The code below does the same thing like the code above but in one line.
// temps = append([]int(nil), temps[len(temps)-10:]...)
// ------------------------------------------------------
// don't worry about this code yet.
api.Report()
fmt.Fprintln(ioutil.Discard, temps[0])
}