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/api"
|
|
|
|
)
|
|
|
|
|
|
|
|
// ---------------------------------------------------------
|
|
|
|
// EXERCISE: Fix the memory leak
|
|
|
|
//
|
2019-08-18 13:29:12 +03:00
|
|
|
// WARNING! This is a very difficult exercise. You need to
|
|
|
|
// do some research on your own to solve it. Please don't
|
|
|
|
// get discouraged if you can't solve it yet.
|
2019-03-05 23:32:32 +03:00
|
|
|
//
|
2019-08-18 13:29:12 +03:00
|
|
|
// Imagine that you receive millions of temperature data
|
|
|
|
// points but you only need the last 10 data points
|
|
|
|
// (temperatures).
|
|
|
|
//
|
|
|
|
// Problem: There is a memory leak in your program.
|
|
|
|
// Please find the leak and fix it.
|
|
|
|
//
|
|
|
|
// Memory leak means: Your program uses computer memory
|
|
|
|
// unnecessarily. See this: https://en.wikipedia.org/wiki/Memory_leak
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// CURRENT OUTPUT
|
|
|
|
//
|
|
|
|
// > Memory Usage: 113 KB
|
|
|
|
// > Memory Usage: 65651 KB
|
2019-03-05 23:32:32 +03:00
|
|
|
//
|
|
|
|
//
|
|
|
|
// EXPECTED OUTPUT
|
|
|
|
//
|
|
|
|
// > Memory Usage: 116 KB
|
|
|
|
// > Memory Usage: 118 KB
|
|
|
|
//
|
|
|
|
//
|
|
|
|
// EXPECTED OUTPUT EXPLANATION
|
|
|
|
//
|
2019-08-18 13:29:12 +03:00
|
|
|
// In the current program, because of the memory leak,
|
|
|
|
// the difference is huge: about ~60 MB. Run the program and,
|
|
|
|
// see it yourself.
|
2019-03-05 23:32:32 +03:00
|
|
|
//
|
2019-08-18 13:29:12 +03:00
|
|
|
// Your goal is reducing the memory usage.
|
2019-03-05 23:32:32 +03:00
|
|
|
//
|
2019-08-18 13:29:12 +03:00
|
|
|
// See the code in api/api.go to see how it allocates
|
|
|
|
// a huge memory.
|
2019-03-05 23:32:32 +03:00
|
|
|
//
|
|
|
|
// ---------------------------------------------------------
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
// reports the initial memory usage
|
|
|
|
api.Report()
|
|
|
|
|
2019-08-18 13:29:12 +03:00
|
|
|
// reads 65 MB of temperature data into memory!
|
2019-03-05 23:32:32 +03:00
|
|
|
temps := api.Read()
|
|
|
|
|
|
|
|
// -----------------------------------------------------
|
|
|
|
// ✪ ONLY ADD YOUR CODE INSIDE THIS BOX ✪
|
|
|
|
//
|
|
|
|
|
|
|
|
//
|
|
|
|
// ✪ ONLY ADD YOUR CODE INSIDE THIS BOX ✪
|
|
|
|
// -----------------------------------------------------
|
|
|
|
|
2019-08-18 13:29:12 +03:00
|
|
|
// dont touch this code.
|
2019-03-05 23:32:32 +03:00
|
|
|
api.Report()
|
2019-08-18 13:29:12 +03:00
|
|
|
|
|
|
|
// don't worry about this code yet.
|
2019-03-05 23:32:32 +03:00
|
|
|
fmt.Fprintln(ioutil.Discard, temps[0])
|
|
|
|
}
|