Performance starts with asking how much work a loop performs as input grows.

operation count Counting simple operations is deterministic and helps explain performance before measuring real time.

Operation Counts

items
operation_counts.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

func main() {
	var items = 4
	visits := 0
	total := 0

	for i := 1; i <= items; i++ {
		visits++
		total += i
	}

	fmt.Println("items=", items)
	fmt.Println("visits=", visits)
	fmt.Println("total=", total)
	fmt.Println("linear=", visits == items)
}
package main

import "fmt"

func main() {
	var items = 2
	visits := 0
	total := 0

	for i := 1; i <= items; i++ {
		visits++
		total += i
	}

	fmt.Println("items=", items)
	fmt.Println("visits=", visits)
	fmt.Println("total=", total)
	fmt.Println("linear=", visits == items)
}
package main

import "fmt"

func main() {
	var items = 6
	visits := 0
	total := 0

	for i := 1; i <= items; i++ {
		visits++
		total += i
	}

	fmt.Println("items=", items)
	fmt.Println("visits=", visits)
	fmt.Println("total=", total)
	fmt.Println("linear=", visits == items)
}
  1. items ← 4, visits ← 0, total ← 0

    5func main() {6  var items→ 4 = 4 //@items=2, 67  visits→ 0 := 08  total→ 0 := 0
  2. visits ← 1, total ← 1

    pass 1 of 4
    10for i1 := 1; i <= items4; i++ {11  visits→ 1++12  total→ 1 += i113}
    All 4 passes — pass 1 is the card above
    passivisitstotal
    110 10 1
    221 21 3
    332 33 6
    443 46 10
  3. fmt.Println("items=", items)

    15  fmt.Println("items=", items4)16  fmt.Println("visits=", visits4)17  fmt.Println("total=", total10)18  fmt.Println("linear=", visits4 == items4)19}
    outputitems= 4
    visits= 4
    total= 10
    linear= true
  1. items ← 2, visits ← 0, total ← 0

    5func main() {6  var items→ 2 = 27  visits→ 0 := 08  total→ 0 := 0
  2. visits ← 1, total ← 1

    pass 1 of 2
    10for i1 := 1; i <= items2; i++ {11  visits→ 1++12  total→ 1 += i113}
  3. visits ← 2, total ← 3

    pass 2 of 2
    10for i2 := 1; i <= items2; i++ {11  visits→ 2++12  total→ 3 += i213}
  4. fmt.Println("items=", items)

    15  fmt.Println("items=", items2)16  fmt.Println("visits=", visits2)17  fmt.Println("total=", total3)18  fmt.Println("linear=", visits2 == items2)19}
    outputitems= 2
    visits= 2
    total= 3
    linear= true
  1. items ← 6, visits ← 0, total ← 0

    5func main() {6  var items→ 6 = 67  visits→ 0 := 08  total→ 0 := 0
  2. visits ← 1, total ← 1

    pass 1 of 6
    10for i1 := 1; i <= items6; i++ {11  visits→ 1++12  total→ 1 += i113}
    All 6 passes — pass 1 is the card above
    passivisitstotal
    110 10 1
    221 21 3
    332 33 6
    443 46 10
    554 510 15
    665 615 21
  3. fmt.Println("items=", items)

    15  fmt.Println("items=", items6)16  fmt.Println("visits=", visits6)17  fmt.Println("total=", total21)18  fmt.Println("linear=", visits6 == items6)19}
    outputitems= 6
    visits= 6
    total= 21
    linear= true