Readability Over Performance
Latest update: November 29, 2022

Readability over Performance #

Go began as (and still is, for a large part) a systems programming language. A sort of, spiritual successor to C and C++. Thus, it was all normal that it inherited many of the low-level constructs and ideas of its predecessors.

Thus, it is not uncommon to see things in Go code, like passing a pointer to a function, which then mutates the value that this pointer points to, instead of returning a new value:

func mulByTwo(ins []int, outs *[]int) {
	for i, _ := range ins {
		*outs = append(*outs, i)
	}
}

func main() {
	ins := []int{1, 2, 3, 4}
	var outs []int
	mulByTwo(ins, &outs)
	fmt.Println(outs)
}

This is a very bad example, I know. Some people might claim that it is easier on the garbage collector, because you are potentially skipping a heap escape, but don’t do it. Unless, you really have a compelling need to squeeze a few performance decimal points, the version below is much easier on both your eyes and your brain:

  • TODO: Link to a possible future chapter on garbage collection
func mulByTwo(ins []int) []int {
	var outs []int
	for i, _ := range ins {
		outs = append(outs, i)
	}
	return outs
}

func main() {
	ins := []int{1, 2, 3, 4}
	outs := mulByTwo(ins)
	fmt.Println(outs)
}