CodeBlanks Logo Icon CodeBlanks

Challenge 2 - Performance

Write a performance analysis that inspects GC and allocs.

Challenge: reduce GC pressure

A log processor creates a new []string for every line:

func alanlar(line string) []string {
    return strings.Split(line, " ")
}

At hundreds of thousands of lines per second this means constant GC. Your task: write alanlarInto(dst []string, line string) []string, which writes the fields into a reusable buffer, and show that allocations in the loop drop to zero.

Plan

Substrings in Go aren't copies but new headers pointing at the same memory, so line[bas:i] doesn't allocate. The function: dst = dst[:0], walk the line character by character, append the piece at each space, append the remainder at the end. Measure: call it repeatedly on the same buf with testing.AllocsPerRun.

Practice Zero allocations

Write alanlarInto. Process the line "GET /api 200 12ms" with buf := make([]string, 0, 8); print the field count and the testing.AllocsPerRun result on one line.

Starter code

main.go
package main

import (
    "fmt"
    "testing"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "testing"
)

func alanlarInto(dst []string, line string) []string {
    dst = dst[:0]
    bas := 0
    for i := 0; i < len(line); i++ {
        if line[i] == ' ' {
            dst = append(dst, line[bas:i])
            bas = i + 1
        }
    }
    return append(dst, line[bas:])
}

func main() {
    line := "GET /api 200 12ms"
    buf := make([]string, 0, 8)
    a := testing.AllocsPerRun(100, func() { buf = alanlarInto(buf, line) })
    fmt.Println(len(buf), a)
}

Expected output

4 0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does the expression <code>dst[:0]</code> do?

  • Returns nil
  • Keeps the capacity and resets the length to zero Correct answer
  • Allocates a new array
  • Deletes the array

Explanation: The same underlying array is kept; append writes from the start without reallocating.

2 Reset the buffer

Question
func alanlarInto(dst []string, line string) []string {
    dst = dst____
    // ...
Answer
func alanlarInto(dst []string, line string) []string {
    dst = dst[:0]
    // ...

Explanation: dst[:0] empties the buffer while keeping its capacity.

3 Expression and cost

Term Meaning
strings.Split A new slice per call
dst[:0] Reuse the buffer
line[a:b] Copy-free substring
AllocsPerRun Allocation measurement

All lessons in Expert