Sobes.tech
Junior — Senior

Optimization and refactoring of existing Go code

livecode

Task condition

It is necessary to refactor the provided Go program fragment. The task involves improving code readability and structure, as well as possibly optimizing memory usage. All functionality should remain unchanged.

func main() {
    var mem runtime.MemStats

    runtime.ReadMemStats(&mem)
    fmt.Printf("Before get(): Alloc = %v MiB\n", mem.Alloc/1024/1024)

    resOfRes := make([][]int, 0, 100)

    for i := 0; i < 50; i++ {
        res := getLastElem()

        runtime.GC()
        runtime.ReadMemStats(&mem)
        fmt.Printf("After getAll(): Alloc = %v MiB, slice: %v\n", mem.Alloc/1024/1024, res)

        resOfRes = append(resOfRes, res)
    }

    fmt.Println()
    _ = resOfRes

    // Now go into loop
    for i := 0; i < 20000; i++ {
        runtime.GC()
        runtime.ReadMemStats(&mem)
        fmt.Printf("Alloc = %v MiB\n", mem.Alloc/1024/1024)
        time.Sleep(time.Second * 2)
    }

    fmt.Println(resOfRes)
}

func getLastElem() []int {
    sl := make([]int, 0, 100000)

    for i := 0; i < 100000; i++ {
        sl = append(sl, i)
    }

    // return last element
    return sl[99999:]
}

Refactoring should focus on:

  • Extracting repetitive operations into separate functions;
  • Improving variable and function names for better self-documentation;
  • Reducing direct calls to garbage collector and memory measurements unless necessary for demonstration;
  • Possibly using more efficient methods for creating and working with slices.